CakePHP from scratch : In this tutorial we will build MVC architecture for Simple CRUD application. For better understanding of CakePHP framework, We will create Model, Views and Controller for this fairly simple application. Tutorial Details Program: CakePHP (PHP) Version (if applicable): CakePHP 1.3 Difficulty: Beginner Estimated Completion Time: 50-60 Minutes Defining a Goal Our [...]
CakePHP from scratch : In this tutorial we will build MVC architecture for Simple CRUD application. For better understanding of CakePHP framework, We will create Model, Views and Controller for this fairly simple application.
Tutorial Details
- Program: CakePHP (PHP)
- Version (if applicable): CakePHP 1.3
- Difficulty: Beginner
- Estimated Completion Time: 50-60 Minutes
Defining a Goal
Our goal is to create Simple CRUD (Create, Read, Update and Delete) Application. Befor we starting, I am assuming that CakePHP installed on your machine and should be ready for development.If no then please go through this tutorial Getting Started With CakePHP.
Download
Lets split the processes we are going to do in this tutorial.
- Create the database.
- Create models.
- Create controllers & views – Read data.
- Create controllers & views – Add data.
- Create controllers & views – Edit data.
- Create controllers & views – Delete data.
Step 1: Create the database.
Before we create database for our application, First we need to understand the application we are going building. Most of programmers first sketch flowcharts that explain step-by-step how the user will interact with the application and how the application will react to their inputs.
Note: Make sure you have created a database to be used with our application and put the configuration parameters into the app/Config/database.php file.
Create a table in the database and name it users. Then give the table the fields shown in Table-Img.
Create this simple table with this MySQL table query by the following CREATE TABLE statement:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `mobile` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
Step 2: Creating Models
Now we have a table in the database, We will need to create a model file to talk to that table and fetch results for the application. In the app/Model directory, create a new file named user.php. This file name conforms with Cake’s naming conventions, and you will need to make sure when creating models that you name the files correctly.
As you can see in the user.php, I extended CakePHP’s AppModel class and declared a variable $name which will be used from our Controller to access the model’s functions.
Step 3: Create controllers & views – Read data.
In the app/Controllers folder, create a new file for the users table in the database. Controllers,
by default, link up to the table after which they are named. In this case, we have created an
users table. So, create a file named users_controller.php in /app/controllers and paste this code.
set('users', $this->User->find('all'));
}
?>
We are extending AppController class, declaring $name variable. This time I added a function called index. The controller functions are called actions.By defining function index() in our UsersController, users can now access the logic there by requesting http://localhost/users/index. Same as, if you want to define a function called foo(), users would be able to access that at http://localhost/users/foo.
“A perfect MVC application’s controller will generally act in this role with most of the custom logic placed here.”
Consider line number 7 in above code in index() function. This is why people (Me too) love CakePHP. With this one line of code, we are selecting all users from users table and assigning the resulting array to users variable. This variable will be available in our index view.
Create View File – index.ctp
In the app/Controllers folder, Create a new folder named Users in this folder create file index.ctp (/app/Views/Users/index.ctp) .ctp files extension are CakePHP template files. Copy/Paste this code in index.ctp.
Html->link('Add New User',array('controller' => 'users', 'action' => 'add')); ?>
Users Data
| Id | First Name | Last Name | Mobile | Actions | |
|---|---|---|---|---|---|
As you can see, index.ctp is simple HTML and PHP mixed file. If you remember, we added all users to a users variable, so we can directly use it in our foreach loop and writing data to a table.
Now its time test what we have done, go to your cake install URL and add/Users (for example http://localhost/cakephp_nettuts/Users). You should see your data as in this image.
Step 5: Create controllers & views – Add data.
Now let spice up more this code.open your users_controller.php and copy/past add() function.
// Add new user data function (C)
function add()
{
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your user data has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
This function is used to insert new data posted from forms. Then the function is saving the data, writing a message and redirecting you back to index function.
Create View File for add() Function – add.ctp
In the /app/Views/Users/ folder, Create a new php file named add.ctp and past this code.
Add New User
Form->create('User');
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('email');
echo $this->Form->input('mobile');
echo $this->Form->end('Save New User');
?>
In this code we are using CakePHP’s form helper to create the form. Now open it (for example http://localhost/cakephp_nettuts/Users/add ) in your browser. We can see the form is to insert new user data. You will see that Cake automatically transformed this code onto a valid form.
create() is called with no parameters supplied, it assumes you are building a form that submits to the current controller’s add() action (or edit() action when id is included in the form data), via POST.
$form->input() method is used to create form elements of the same name. The first parameter tells CakePHP which field they correspond to, and the second parameter allows you to specify a wide array of options – in this case, the number of rows for the textarea. There’s a bit of introspection and automatic here: input() will output different form elements based on the model field specified.
$form->end() call generates a submit button and ends the form. If a string is supplied as the first parameter to end(), the FormHelper outputs a submit button named accordingly along with the closing form tag.
Now let’s go back and update our /app/views/users/index.ctp view to include a new “Add Post” link. Just after.
Step 5: Create controllers & views – Edit data.
Let us develop our functionality for editing the Users. But, before that we need to add edit & delete link in index.ctp. I will deleting deleating users after this step.
Open your index.ctp file and update with this code.
Html->link('Add New User',array('controller' => 'users', 'action' => 'add')); ?>
Users Data
| Id | First Name | Last Name | Mobile | Actions | |
|---|---|---|---|---|---|
| . | Html->link('Edit', array('action'=>'edit', $user['User']['id']));?> | Html->link('Delete', array('action' => 'delete', $user['User']['id']), null, 'Are you sure?' )?> |
Now, lets create function for editing users in our controller. Open your /app/controllers/users_controller.php and add this new function edit().
//Update user data function (U)
function edit($id = null) {
$this->User->id = $id;
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your user with id: '.$id.' has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
As we can see the code, This function first checks for submitted form data. If nothing was submitted, it finds the User and hands it to the view. If some data has been submitted, try to save the data using User model
Create View File for edit() Function – edit.ctp
We need to create View for this edit function, create /app/Views/Users/edit.ctp file.
Edit User
Form->create('User', array('action' => 'edit')); echo $this->Form->input('id', array('type'=>'hidden')); echo $this->Form->input('first_name'); echo $this->Form->input('last_name'); echo $this->Form->input('email'); echo $this->Form->input('mobile'); echo $this->Form->end('Update User'); ?>
This edit.ctp file outputs the edit form with the values.
Step 6: Create controllers & views – Delete data.
The easiest step, Create new function delete() in /app/Controllers/users_controller.php file.
// Delete user data function (D)
function delete($id)
{
$this->User->delete($id);
$this->Session->setFlash('The user with id: '.$id.' has been deleted.');
$this->redirect(array('action'=>'index'));
}
This function only deletes the user and redirects back to index action of the Users controller, no need to create a view for this function.
To test your application open this url in your browser.
Display data : http://localhost/cakephp_nettuts/Users/
Add new data: http://localhost/cakephp_nettuts/Users/add/
Download
Congratulations, you finished your Simple CRUD Application in CakePHP!













5 Responses
Thanks Ajay !! Your post finally helped me in understanding the basics of cakephp framework. I stumbled upon several posts and tutorials before this, however, I could not see an end-to-end example anywhere. Even the tutorials and examples from cakephp.org itself, viz the blog example at http://book.cakephp.org/2.0/en/tutorials-and-examples.html didnt help me in the way your post has.
Cheers Again !!
Hi thanks a lot ajay, I have visited so many tutorial web site but it was difficult to understand basic start with cake.
But your article is ver
Hi thanks a lot ajay, I have visited so many tutorial web site but it was difficult to understand basic start with cake.
But your article is very easy to understand cake.
Very good and easy tutorial to learn cakephp initials for the beginners.I have learn so many concepts with tutorial.
Thanks for awesome tutorial. It really helps me a lot