CakePHP is an open source web-application rapid development framework and it is written in php. It was started in April 2005.

CakePHP perform a lot of tasks automatically, like generating a web-form from database tables -with all validation rules- , Integrating ajax, creating sophisticated method without compromising with security or application performance.

CakePHP follows the MVC( Model – View – Controller)software design pattern. Programming using MVC separates your application into three main parts:

  1. The Model represents the application data
  2. The View renders a presentation of model data
  3. The Controller handles and routes requests made by the client
cakephp mvc

A Basic MVC Request

Some features of CakePHP are,

  • Active,Friendly community.
  • Flexible licensing.
  • Compatible with versions PHP 5.2.8 and greater.
  • Integrated CRUD(Create,Read,Update,Delete) for database interaction.
  • Application scaffolding(programming).
  • Code generation.
  • MVC (Model,View,Controller) architecture.
  • Request dispatcher with clean,custom URLs and routes
  • Built-in validation
  • Fast and flexible templating(PHP syntax with helpers).
  • View helpers for AJAX,JavaScript,HTML forms and more.
  • Email,Cookie,Security,Session and requset handling components.
  • Flexible ACL(Access Control List).
  • Data Sanitization.
  • Flexible caching.
  • Localization.
  • Works from any website directory,with littile to no Appache configuration involved.


2. Latest version of CakePHP and how it differ from previous release ?

Latest version of Cakephp 2.3.1 released now.It is a fully API compatible upgrade from cakephp 2.2.

Cakephp versions has the difference between using public and var. In Cakephp 2.0 and later the code is


class PostsController extends Appcontroller


     public $helpers = array(‘Html’,’Form’);

     public $name = ‘Posts’;

     public function index()


         $this->set(‘posts’,$this->Post->find( ‘all’ ));




Older version code is,


 class PostsController extends Appcontroller


     var $helpers = array(‘Html’,’Form’);

     var $name = ‘Posts’;

     function index()


         $this->set(‘posts’,$this->Post->find( ‘all’ ));




Here the ”var” is deprecated visibility keyword that is functionality equal to “public” .

The main changes of 2.3.1 are the following,

  • The ServerShell now correctly handles plugin and theme assets.
  • FormHelper::inputs() now correctly handles plugin models.
  • Backwards compatibility for HABTM checkboxes has been improved.
  • Schema generation works better with SQLServer now.
  • Baking models better detects has and belongs to many associations.
  • Security::rijndael() now correctly generates random iv values. It will continue to decrypt values encrypted with a fixed iv. This improves security of encrypted values, by preventing dictionary attacks on the key/value.
  • Altering tables with Postgres properly renames fields now.
  • Regular expression operators are better supported in Postgres.
  • Fatal errors now display when gzip encoding is enabled.
  • Model whitelists are restored when a save() fails due to no data, when a model has no created/updated fields.
  • Validation::$errors is no longer populated with booleans, this prevents memory consumption issues in longer running scripts.


An application can easily defines cache and logs, as they are conditionally defined by CakePhp.


File engine is always the default cache engine.

Configure::write(‘Cache.viewPrefix,YOURPREFIX’); has been added to core.php to allow multiple domains/languages per setup.


Auth component

A new property Authcomponent :: $unauthorizedRedirect has been added. For default true value user is redirected to referrer url upon authorization failure. A new authenticate adapter has been added to support blowfish/bcrypt hashed passwords.

AuthComponent :: redirect() has been deprecated. Use AuthComponent :: redirectUrl() instead.

Paginator Component

Paginator component now support the “findType” Option.

Paginator Component now throws a NotFoundException when trying to access a page which is out of range (i.e. requested page is greater than total page count).

Security Component

SecurityComponent now supports the unlocked Actionsoption. This can be used to disable all security checks for any actions listed in this option.

Request Handler Component

RequestHandlerComponent :: viewClassMap() has been added ,whcich is used to map a type to view classname. Add $settings[‘viewClassMap’] for automatically setting the correct viewClass based on extension/content type.

Cookie Component

CookieComponent :: check() was added. This method works the same as CakeSession :: check() does.


Cake Plugin

CakePlugin::load()can now take a new ignoreMissing option. Setting it to true will prevent file include errors when you try to load routes or bootstrap . So use the following statement, which will load all plugins and their routes and bootstrap for whatever plugin it can find find::CakePlugin::loadAll(array(‘routes’ => true, ‘bootstrap’ => true, ‘ignoreMissing’ => true))


Configure ::check() was added. This method works the same as CakeSession ::check() does.

ConfigReaderInterface ::dump() was added.

The $key parameter of IniReader :: dump() now supports keys like PluginNane.keyname


CakeBaseException was added,which all core Exceptions now extend. The base exception class also introduces the responseHeader() method which can be called on created Exception instances to add headers for the response, as Exceptions dont reuse any response instance.


Support for the biginteger type was added to all core datasources, and fixtures.

Support for FULLTEXT indexes was added for the MySQL driver. Model::find(‘list’) now sets the recursive based on the max containment depth or recursive value. When list is used with ContainableBehavior.

Model::find(‘first’) will now return an empty array when no records are found.


Missing validation methods will always trigger errors now instead of only in development mode.


Smtp Transport

TLS/SSL support was added for SMTP connections.

CakeRequest :: onlyAllow(); and CakeRequest :: Query() was added.


CakeResponse :: file() was added.The content types application/javascript, application/xml, application/rss+xml now also send the application charset.


The contentDisposition option was added to CakeEmail :: attachments().This allows to disable the Content-Disposition header added to attached files.


HttpSocket now verifies SSL certificates by default. HttpResponse was renamed to HttpSocketResponse. This avoids a common issue with the http pecl extension. There is an HttpResponse class provided as well for compatibility reasons.


Support for tel:, sms: were added to>Router:url().


MediaView is deprecated, and you can use new features in CakeResponse.

Serialization in Json and Xml views has been moved to _serialize().

beforeRender and afterRender callbacks are now being called in Json and Xml views when using view templates.

View :: fetch() now has a $default argument. This argument can be used to provide a default value should a block be empty.

View :: prepend() has been added to allow prepending content to existing block.

XmlView now uses the _rootNode view variable to customize the top level XML node.

View::elementExists() was added. This method to check if elements exist before using them.

View :: element() had the ignoreMissing option added. This to suppress the errors triggered by missing view elements.

View :: startIfEmpty() was added.


The doctype for layout files in the app folder and the bake templates in the cake package has been changed from XHTML to HTML5.


New property Helper::$settings has been added for your helper setting. The $settings parameter of Helper::__construct() is merged with Helper::$settings.


FormHelper ::select() accepts a list of values in the disabled attribute. Combined with ‘multiple’ => ‘checkbox’, this allows you to provide a list of values you want disabled.

FormHelper ::postLink() accepts a method key. This allows you to create link forms using HTTP methods other than POST.

When creating inputs with FormHelper :: input() you can now set the errorMessage option to false. This will disable the error message display, but leave the error classnames intact.

The FormHelper now also adds the HTML5 required attribute to input elements based on validation rules for a field. If you have a “Cancel” button in your form which submits the form then you should add ‘formnovalidate’ => trueto your button options to prevent the triggering of validation in html. You can also prevent the validation triggering for the whole form by adding ‘novalidate’ => true in your FormHelper::create() options.

FormHelper :: input() now generates input elements of type tel and email based on field names if type option is not specified.

Html Helper

HtmlHelper :: getCrumbList () now has the separator, firstClass and lastClass options. These allow you to better control the HTML this method generates.


TextHelper :: tail() was added to truncate text starting from the end.

ending in TextHelper :: truncate() is deprecated in favor of ellipsis


PaginatorHelper :: numbers()now has a new option currentTag to allow specifying extra tag for wrapping current page number.

For methods: PaginatorHelper :: prev() and PaginatorHelper :: next() it is now possible to set the tag option to false to disable the wrapper. Also a new option disabledTag has been added for these two methods.


A core fixture for the default cake_sessions table was added. You can use it by adding core.cake_sessions to your fixture list.

CakeTestCase::getMockForModel() was added. This simplifies getting mock objects for models.



The following was added,
CakeNumber :: fromReadableSize(),

CakeNumber :: formatDelta(),

CakeNumber :: defaultCurrency()


Folder :: copy() and Folder :: move() now support the ability to merge the target and source directories in addition to skip/overwrite.


String::tail() was added to truncate text starting from the end.

ending in String :: truncate() is deprecated in favor of ellipsis.


Debugger :: exportVar() now outputs private and protected properties in PHP >= 5.3.0.


Support for bcrypt was added.


Validation :: fieldSize() was added


ObjectCollection::attached() was deprecated in favor of the new method ObjectCollection::loaded(). This unifies the access to the ObjectCollection as load()/unload() already replaced attach()/detach().


3. Why one should use cakephp?

            A significant amount of development time with PHP is spent rewriting common code for routine operations such as database access or returning data to the browser. Of course, all this routine code can quickly become disorganized in traditional PHP applications. What is needed is a framework for PHP that does what Ruby On Rails did for Ruby.

         CakePHP has been around for awhile and does exactly that. It provides a number of useful libraries in support of common tasks and includes facilities for organizing code in folders and associating code with files. As a result, time spent writing and organizing code becomes greatly reduced.

Below are just a few things CakePHP offers to make development easier.

  • Free Open-Source MIT(Massachusetts Institute of Technology) License allowing you to use CakePHP applications within any of your own projects.
  • Compatibility with both PHP4 and PHP5. The minimum version needed is 4.3.2.
  • Support for MySQL, PostgreSQL SQLite, PEAR-DB and wrappers for ADODB, a database abstraction library.
  • Model-View-Controller layout.
  • Easy CRUD (Create, Read, Update and Delete) database interaction.
  • Scaffolding (Application scaffolding is a technique that allows a developer to define and create a basic application that can create, retrieve, update and delete objects. Scaffolding in CakePHP also allows developers to define how objects are related to each other, and to create and break those links.) to save production time.
  • Search Engine Friendly URLS.
  • Input validation and sanitization (The CakePHP Sanitize class can be used to rid user-submitted data of malicious data and other unwanted information. Sanitize is a core library, so it can be used anywhere inside of your code, but is probably best used in controllers or models.) tools to make your applications much more secure.
  • Templating with familiar PHP syntax.
  • Caching Operations.



          CakePHP is an open-source framework for PHP intended to make developing, deploying and maintaining applications much easier. CakePHP offers many useful design patterns, such as the Model-View-Controller pattern.The CakePHP framework also provides a slew of valuable reusable libraries for dealing with common tasks. CakePhp reduces devlopement costs and helps developers write less code.In CakePhp, all directories or folders may look a little daunting at first, but the separate directories are meant to better organize all of the framework components. Since names like “tmp” aren’t self-explanatory here is what these folders are for:

  • The cake folder stores all the core functions and internals for CakePHP.
  • The docs folder contains very little, but does hold the license information (COPYING.txt), a change log and some other useful files. This directory is not important for CakePHP to run so you can remove it if you wish.
  • The app folder is where your application code will go. The app folder will hold your controllers, configuration, templates and much more.
  • The config folder contains all the configuration files for the application. This includes database details, access list, inflections and routes (URL rewriting).
  • The models folder stores all the sql database functionality for your application.
  • The views folder stores all the templates, layouts (header, footer) and helper modules that assist functionality (such as AJAX).
  • The controllers folder stores all the controllers for your application. A controller is the part of the application that directs and controls the model and the views by accepting input and deciding what to do with it.
  • The plugins folder stores plugins which are a combination of models, views and controllers that can be packaged and used in other applications. Examples are user management modules or an RSS module.
  • The tmp folder stores cache files generated by the caching system and also stores debugging logs. This folder will be very valuable during development.
  • The vendors folder, can contain other libraries that you want to include in a particular application.
  • The webroot folder stores static media such as CSS, images and the JavaScript needed by your application.
  • The second vendors directory will allow you to store third-party libraries and hook into them from your CakePHP controllers. For example if we wanted to built a Facebook application with CakePHP we could drop in the Facebook library and configure CakePHP to load it.


To Create Sample Application in CakePhp

Step1: Download the latest cakephp framework from here

Step2: Unzip the files and understand the directory / folder structure.

Example : Here rename the cake php folder as “PasteBin”

Step3: Rename this file /app/config/database.php.default as /app/config/database.php

Step4: Configure CakePHP’s database file /app/config/database.php.

var $default = array(
    ‘driver’ => ‘mysql’,
    ‘persistent’ => ‘false’,
    ‘host’ => ‘localhost’,
    ‘port’ => ”,
    ‘login’ => ”,
    ‘password’ => ”,
    ‘database’ => ”,
    ‘schema’ => ”,
    ‘prefix’ => ”,
    ‘encoding’ => ”

Step5: Configure CakePHP to suite your working environment.

Step6: Define and create your application tables in your mySQL database.

                        Our sample application name is PasteBinApplication. Hence, table name will be “paste_details”.

CREATE TABLE IF NOT EXISTS `paste_details` (

`id` bigint(20) NOT NULL AUTO_INCREMENT,

`groupid` bigint(20) DEFAULT NULL,

`userid` bigint(20) DEFAULT NULL,

`pastename` varchar(400) NOT NULL,

`pasteexpiry` varchar(100) NOT NULL,

`currenttime` time NOT NULL,

`createddate` int(18) NOT NULL,

`pastetext` varchar(600) NOT NULL,

`deleteflag` varchar(15) NOT NULL,



Step7: Define the Model.

           By creating a CakePHP model that will interact with our database, we’ll have the foundation in place needed to do our view, add, edit, and delete operations later. CakePHP’s model class files go in /app/models, and the file we’ll be creating will be saved to /app/models/user.php. The completed file should look like this:

Example :User.php, Pastedetails.php

class User extends AppModel {
    var $name = ‘User’;

          Naming convention is very important in CakePHP. By naming our model User, CakePHP can automatically infer that this model will be used in the usersController, and will be tied to a database table called users.CakePHP will dynamically create a model object for you, if it cannot find a corresponding file in /app/model. This also means, that if you accidentally name your file wrong (i.e. User.php or users.php) CakePHP will not recognize any of your settings and will use the defaults instead.The $name variable is always to add, and is used to overcome some class name oddness in PHP4.

Step8: Define the Controller.

         Next, we’ll create a controller for our users. The controller is where all the logic for user interaction will happen. We’ll place this new controller in a file called UsersController.php inside the /app/controller directory. Here’s what the basic controller should look like:

class UsersController extends AppController {
    Public $helpers = array (‘Html’,’Form’);
    Public $name = ‘Users’;

         By defining function login() in our UsersController, users can now access the logic there by requesting localhost/users/login. Should follow CakePHP conventions (plural controller names, etc.) and create readable, understandable action names.

Step9: Define the View.

               Cake’s view files are stored in /app/view inside a folder named after the controller they correspond to (we’ll have to create a folder named ‘Users’ in this case). To format this post data in a nice table, our view code might look something like this:

<div class=“users form”>

<form method=“post” class=“users form”>

<?php echo $this->Session->flash(‘auth’); ?>

<?php echo $this->Form->create(‘User’); ?>

<fieldset style=”width:60%;”>

<legend><?phpecho __(‘Please enter your username and password’); ?></legend>

<table style=”width:60%;”>

<tbody >


<td>UserName<font color=red>*</font></td><td><input type=“text” size=“10” name=“data[User][username]” ></td>



<td>Password<font color=red>*</font></td><td><input type=“password” size=“10” name=“data[User][password]”></td>




</fieldset><font color=red>*</font> Required fields cannot be blank !!!!

<?phpecho $this->Form->end(__(‘Login’));?><div style=”margin-top: -50px; margin-left: 86px;”><a href=“createnewuser” style=”text-decoration:none;”><font color=Blue>SignUp</font></a></div>



Step10: Run the application through your browser http://localhost/yourApp/

Example : http://localhost/PasteBin/

Step11: Test and Readjust the Views to suite your application needs.

Step12: Let’s create a shell for use in the Console. For this example, we’ll create a PastedetailsShell for delete the posted text within a specific time. In your applications Console/Command directory create PastedetailsShell.php. The conventions for shell classes are that the class name should match the file name, with the suffix of Shell. In our shell we created a main() method. This method is called when a shell is called with no additional commands.

From your application directory, run: /PasteBin/app/Console/cake Pastedetail

Following are some screenshots after creating the “PasteBinApplication”

1. Login Page



2. Login Page With Validation



3. SignUp Page for New Users



4. Create new Paste Page for Guest User – shows all Public Posts



5. ‘CreateNewPaste’ Page for valid User – only shows corresponding user posts.


The full source code of PasteBin Application can be downloaded from here