Model, Controller and View in CakePHP

Model, Controller and View in CakePHP

All is well. What you say? I say so. In previous tutorial, we have learnt some very important theories about CakePHP. If you understand, your journey will be easier with this professional framework. Before start, I assume you have already read previous tutorial. If not, read that one first. Then come here. Ohh.. forgot to mention. Lot’s of surprise is waiting for you.

Cake logo

CakePHP Request

We’ve covered the basic ingredients in CakePHP, so let’s look at how objects work together to complete a basic request. Continuing with our original request example, let’s imagine that our friend Ricardo just clicked on the “Buy A Custom Cake Now!” link on a CakePHP application’s landing page.


Black = required element, Gray = optional element, Blue = callback

  1. Ricardo clicks the link pointing to, and his browser makes a request to your web server.
  2. The Router parses the URL in order to extract the parameters for this request: the controller, action, and any other arguments that will affect the business logic during this request.
  3. Using routes, a request URL is mapped to a controller action (a method in a specific controller class). In this case, it’s the buy() method of the CakesController. The controller’s beforeFilter() callback is called before any controller action logic is executed.
  4. The controller may use models to gain access to the application’s data. In this example, the controller uses a model to fetch Ricardo’s last purchases from the database. Any applicable model callbacks, behaviors, and DataSources may apply during this operation. While model usage is not required, all CakePHP controllers initially require at least one model.
  5. After the model has retrieved the data, it is returned to the controller. Model callbacks may apply.
  6. The controller may use components to further refine the data or perform other operations (session manipulation, authentication, or sending emails, for example).
  7. Once the controller has used models and components to prepare the data sufficiently, that data is handed to the view using the controller’s set() method. Controller callbacks may be applied before the data is sent. The view logic is performed, which may include the use of elements and/or helpers. By default, the view is rendered inside of a layout.
  8. Additional controller callbacks (like afterFilter) may be applied. The complete, rendered view code is sent to Ricardo’s browser.

You already know what you need to know to code with CakePHP. In this tutorial, we will learn how to read data from our database. You can also check out ServiceMax connected field service solution helping enterprise companies increase technician productivity and customer satisfaction.

Step :1

Create a database named cakedb. Then, create a table called posts from following script –

CREATE TABLE posts (     
title VARCHAR(50),     
body TEXT, 
funnypost TINYINT(1),
seriouspost TINYINT(1),

INSERT INTO `posts` (`id`, `title`, `body`, `funnypost`, `seriouspost`, `created`, `modified`) VALUES
(1, 'First post', 'This is my first post.', 1, 0, '2014-03-22 16:41:48', '2014-03-22 16:41:48'),
(2, 'Second post', 'This is my second post.', 0, 1, '2014-03-22 16:42:24', '2014-03-22 16:42:24'),
(3, 'Third post.', 'This is my third post', 1, 0, '2014-03-22 16:42:48', '2014-03-22 16:42:48'),
(4, 'Fourth post', 'This is my fourth post.', 1, 0, '2014-03-22 16:44:13', '2014-03-22 16:44:13'),
(5, 'Fifth post', 'This is my fifth post.', 0, 1, '2014-03-22 16:44:47', '2014-03-22 16:44:47'),
(6, 'Sixth post', 'This is my sixth post.', 1, 1, '2014-03-22 17:26:25', '2014-03-22 17:26:25');

Step 2:
Now create a project called cakephp24 inside your htdocs. Rename your database configuration file to database.php from database.php.default in app/Config. Configure the default database like –

public $default = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'root',
		'password' => '',
		'database' => 'cakedb',
		'prefix' => '',
		//'encoding' => 'utf8',

Step 3:
Create a model to app/Model/Post.php. Write the following simple code –

App::uses('AppModel', 'Model');
 * Post Model
class Post extends AppModel {


Code Explanation
In line 1, we have added AppModel and Model class. It is a good practice to add classes before use.

In line 6, we have created a simple Post model class. It is blank. Because all the business logic will be exist in controller class, in CakePHP.

Step 4:
Now, create a controller class to app/Controller/PostsController.php. Write the following code –

App::uses('AppController', 'Controller');

 * Posts Controller
class PostsController extends AppController

     * Components
    public $components = array('Paginator');

     * index method
    public function index()
        $this->Post->recursive = 0;
        $this->set('posts', $this->Paginator->paginate());

Code Explanation
In line 1, we have added AppController and Controller class for our convenience.

Line 6, we have created our controller. Remember the conventions from previous tutorial? It works same everywhere in CakePHP.

In line 12, we have added components to use. CakePHP components are the packages that are shared between controllers. Like, Pagination, Sessions, Authentication, Security, Cookie etc.

In line 20, we have created paginator in our post.

Step 5:
Now the last task, create our view as app/View/Posts/index.ctp. Write the following code –

<div class="posts index">
	<h2><?php echo __('Posts'); ?></h2>
	<table cellpadding="0" cellspacing="0">
			<th><?php echo $this->Paginator->sort('id'); ?></th>
			<th><?php echo $this->Paginator->sort('title'); ?></th>
			<th><?php echo $this->Paginator->sort('body'); ?></th>
			<th><?php echo $this->Paginator->sort('funnypost'); ?></th>
			<th><?php echo $this->Paginator->sort('seriouspost'); ?></th>
			<th><?php echo $this->Paginator->sort('created'); ?></th>
			<th><?php echo $this->Paginator->sort('modified'); ?></th>
	<?php foreach ($posts as $post): ?>
		<td><?php echo h($post['Post']['id']); ?>&nbsp;</td>
		<td><?php echo h($post['Post']['title']); ?>&nbsp;</td>
		<td><?php echo h($post['Post']['body']); ?>&nbsp;</td>
		<td><?php echo h($post['Post']['funnypost']); ?>&nbsp;</td>
		<td><?php echo h($post['Post']['seriouspost']); ?>&nbsp;</td>
		<td><?php echo h($post['Post']['created']); ?>&nbsp;</td>
		<td><?php echo h($post['Post']['modified']); ?>&nbsp;</td>
<?php endforeach; ?>
	echo $this->Paginator->counter(array(
	'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
	?>	</p>
	<div class="paging">
		echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
		echo $this->Paginator->numbers(array('separator' => ''));
		echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));

Code Explanation

From line 5 -11, we have added pagination controls for our view. It creates sorting functionality for every field.

Line 15 – 21, we have printed our posts.

From line 26 – 36 we have created paginator counter and buttons in our view.

We are all done. Now go to –


You will find something like –


Hope, you have get some idea about, CakePHP coding style. It may look like little bit trickier then other very popular framework. But, always remember, CakePHP is the oldest member of this industry. And you should know, old is gold.

Happy coding… 🙂

Model, Controller and View in CakePHP

One comment to “Model, Controller and View in CakePHP”

Leave a Reply

Your email address will not be published. Required fields are marked *