CakePhp is a free,open-source framework of php.It’s a foundational structure for programmers to create web applications. CakePHP provides an extensible architecture for developing ,maintaining,and deploying applications. CakePHP reduces development cost and helps developers write less code. Key features
- Active,friendly
- Built-in validation
- MVC(Model View Controller)architecture
Cake is based on an MVC-like architecture that is both powerful and easy to grasp: controllers, models and views guarantee a strict but natural separation of business logic from data and presentation layers.MVC is a design pattern that simplifies application development and maintence. View for the user to see,Model for the connection between DB and application and controller is the big boss who controlled everything.In MVC archietecture the tasks are seperated in to Model,View and Controller that makes the application light. Modular and seperate programming allows developers and designers to work simultaneously.The application are seperated into three components.
Models are active representations of database tables: they can connect to your database, query it (if instructed to do so by a controller) and save data to the database. It is important to note that in order to correctly apply the MVC architecture, there must be no interaction between models and views: all the logic is handled by controllers.
Views can be described as template files that present their content to the user: variables, arrays and objects that are used in views are registered through a controller. Views should not contain complex business logic; only the elementary control structures necessary to perform particular operations, such as the iteration of collected data through a foreach construct, should be contained within a view.
Controllers contain the logic of your application. Each controller can offer different functionality; controllers retrieve and modify data by accessing database tables through models; and they register variables and objects, which can be used in views.Controller merges Styling of View with the functionality of Model.
1. Basic Principles Of CakePhp
The framework provides a basic organizational structure, from filenames to database table names, keeping entire application consistent and logical. This concept is simple but powerful. Follow the conventions and always know exactly where things are and how they’re organized.
1.1 CakePhp Structure
CakePHP features Controller, Model, and View classes, but it also features some additional classes components,Behaviours and helpers
- components : A Component is a class that aids in controller logic. If you have some logic you want to share between controllers (or applications), a component is usually a good fit.
- Behaviours : Behaviors work as ways to add common functionality between models.Models also are supported by another class called a DataSource. DataSources are an abstraction that enable models to manipulate different types of data consistently.
- Helpers : A Helper is a class that aids in view logic. Much like a component used among controllers, helpers allow presentational logic to be accessed and shared between views. One of the core helpers, AjaxHelper, makes Ajax requests within views much easier.Most applications have pieces of view code that are used repeatedly. CakePHP facilitates view code reuse with layouts and elements. By default, every view rendered by a controller is placed inside a layout. Elements are used when small snippets of content need to be reused in multiple views.
1.2 CakePHP Request
Black = required element, Gray = optional element, Blue = callback
- When a Client clicks the link his browser makes a request to your web server.
- 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.
- 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.
- 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.
- After the model has retrieved the data, it is returned to the controller. Model callbacks may apply.
- The controller may use components to further refine the data or perform other operations
- 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.
- Additional controller callbacks (like afterFilter) may be applied. The complete, rendered view code is sent to Client’s browser.
1.3 CakePhp Folder Structure
Files and folders are
- app
- cake
- vendors
- .htaccess
- index.php
- README
- app is the folder where applications are placed editing is possible
- cake is the folder where the actual core code is placed .
- vendors folder is where you’ll place third-party
Application development will be done at app .Folders inside of app are
- config
- controllers
- locale
- models
- plugins
- tmp
- vendors
- views
- webroot
- config holds olds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.
- Controller Contains your application’s controllers and their components.
- Model Contains your application’s models, behaviors, and datasources.
- Plugin Contains plugin packages.
- Tmp ,this is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information
- Any third-party classes or libraries should be placed at vendors.
- Presentational files are placed at view: elements, error pages, helpers, layouts, and view files.
- In a production setup, webroot should serve as the document root for your application
- cake/
- config/
- docs/
- libs/
2 CakePhp Convensions
1.2.1 File and Classname Convensions
Filenames are underscored while classnames are CamelCased
1.2.2 Model and Database Convensions
Model classnames are singular and CamelCased.Person, BigPerson, and ReallyBigPerson are all examples of conventional model names.Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.All tables with which CakePHP models interact (with the exception of join tables), require a singular primary key to uniquely identify each row.CakePHP does not support composite primary keys.Join tables, used in hasAndBelongsToMany (HABTM) relationships between models should be named after the model tables they will join in alphabetical order (apples_zebras rather than zebras_apples).Field names are by convention lowercase and separated by underscores.
2.3 Controller Convensions
Controller classnames are plural, CamelCased, and end in Controller. PeopleController and LatestArticlesController are both examples of conventional controller names.
The first method you write for a controller might be the index() method. When a request specifies a controller but not an action, the default CakePHP behavior is to execute the index() method of that controller. Visibility of controller methods in CakePHP can be changed by prefixing controller method names with underscores. If a controller method has been prefixed with an underscore, the method will not be accessible directly from the web but is available for internal use. Example
[php]
<?php
class NewsController extends AppController
{
function latest()
{
$this->_findNewArticles();
}
function _findNewArticles()
{
//Logic to find latest news articles
}
}
?>
[/php]
2.4 Url Considerations for getting a controller Name
Urls are lowercase and underscored.For Example if the controller name is RedApplesController and the method name is go_pick ,red_apples/go_pick is the correct form to access
2.5 View Convensions
View template files are named after the controller functions they display, in an underscored form. The getReady() function of the PeopleController class will look for a view template in /app/views/people/get_ready.ctp.
The basic pattern is /app/views/controller/underscored_function_name.ctp.By naming the pieces of your application using CakePHP conventions, you gain functionality without the hassle and maintenance tethers of configuration. Here’s a final example that ties the conventions
- Database table: “people”
- Model class: “Person”, found at /app/models/person.php
- Controller class: “PeopleController”, found at /app/controllers/peoples_controller.php
- View template, found at /app/views/people/index.ctp
Using these conventions, CakePHP knows that a request to http://example.com/people/ maps to a call on the index() function of the PeopleController, where the Person model is automatically available (and automatically tied to the ‘people’ table in the database), and renders to a file. None of these relationships have been configured by any means other than by creating classes and files that you’d need to create anyway.
3 Developing With CakePhp
3.1 Requirements
- has access to a web server like Apache, although others like IIS and Lighttpd are supported
- has the ability to rewrite URLs (e.g. using the mod_rewrite module for Apache — by default CakePHP comes with a .htaccess file to handle this)
- has MySQL, or a similar database server installed, and you have the necessary privileges to create a new database; other solutions like PostgreSQL or Microsoft SQL Server or SQLite or Oracle should work, although MySQL is recommended (this example will assume that you are using MySQL)
- has PHP version 4.3 or above; CakePHP seamlessly supports both PHP4 and PHP5
- Give write permission to “/app/tmp” folder.
3.2 Installation Preparation
Installation preparation consists of the following steps:
- Downloading a copy of CakePHP
- Configuring your web server to handle php if necessary
- Checking file permissions
3.3 Configuration
3.3.1 Database Configuration
CakePHP expects database configuration details to be in a file at app/config/database.php. An example database configuration file can be found at app/config/database.php.default.Make a copy of this file in the same directory, but name it database.php.A finished configuration should look something like this.
[php]
var $default = array(‘driver’ => ‘mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘login’ => ‘cakephpuser’,
‘password’ => ‘c4k3roxx!’,
‘database’ => ‘my_cakephp_project’,
‘prefix’ => ”);
[/php]
3.3.2 Core Configuration
There are three other items that can be configured. One is defining a custom string (or “salt”) for use in security hashes. The second is defining a custom number (or “seed”) for use in encryption. The third item is allowing CakePHP write access to its tmp folder.
The security salt is used for generating hashes. Change the default salt value by editing /app/config/core.php line 203. It doesn’t much matter what the new value is, as long as it’s not easily guessed.
[php]
<?php
/**
* A random string used in security hashing methods.
*/
Configure::write(‘Security.salt’, ‘pl345e-P45s_7h3*S@l7!’);
?>
[/php]
The cipher seed is used for encrypt/decrypt strings. Change the default seed value by editing /app/config/core.php line 208. It doesn’t much matter what the new value is, as long as it’s not easily guessed.
[php]
<?php
/**
* A random numeric string (digits only) used to encrypt/decrypt strings.
*/
Configure::write(‘Security.cipherSeed’, ‘7485712659625147843639846751’);
?>
[/php]
The final task is to make the app/tmp directory web-writable. The best way to do this is to find out what user your webserver runs as () and change the ownership of the app/tmp directory to that user. The final command might look something like this.
$ chown -R www-data app/tmp
3.4 Controllers
A controller is used to manage the logic for a part of your application.Controllers can include any number of methods which are usually referred to as actions. Actions are controller methods used to display views. An action is a single method of a controller.CakePHP’s dispatcher calls actions when an incoming request matches a URL to a controller’s action .For example RecipesController might contain the view(), share(), and search() actions. The controller would be found in /app/controllers/recipes_controller.php and contain:
[php]
<?php
# /app/controllers/recipes_controller.php
class RecipesController extends AppController {
function view($id) {
//action logic goes here..
}
function share($customer_id, $recipe_id) {
//action logic goes here..
}
function search($query) {
//action logic goes here..
}
}
?>
[/php]
- APP controller:AppController class is the parent class to all of your application’s controllers. AppController itself extends the Controller class included in the CakePHP core library.Controller attributes and methods created in your AppController will be available to all of your application’s controllers. It is the ideal place to create code that is common to all of your controllers.
- Pages Controller:The home page after installation is generated using this controller. It is generally used to serve static pages. Eg. If you make a view file app/views/pages/about_us.ctp
- Controller Attributes
- $name: The $name attribute should be set to the name of the controller. Usually this is just the plural form of the primary model the controller uses.
- # $name controller attribute usage example
[php]
class RecipesController extends AppController {<br /><br />
var $name = ‘Recipes’;<br /><br />
}
?>
[/php] - $Components,$uses,$helpers:
- The Html, Form, and Session Helpers are always available by default, as is the SessionComponent
- If you do not wish to use a Model in your controller, set var $uses = array(). This will allow you to use a controller without a need for a corresponding Model file.
Controllers have access to their primary model available by default.However, when allowing a controller to access additional models through the $uses variable, the name of the current controller’s model must also be included.
[php]
<?php
class RecipesController extends AppController
{
var $name = ‘Recipes’;
var $uses = array(‘Recipe’, ‘User’);
var $helpers = array(‘Ajax’);
var $components = array(‘Email’);
}
?>
[/php]
3.4.1 Controller Methods
1.Set() : set(string $var, mixed $value)
The set() method is the main way to send data from your controller to your view. Once you’ve used set(), the variable can be accessed in your view.
[php]
<?php
//First you pass data from the controller:
$this->set(‘color’, ‘pink’);
//Then, in the view, you can utilize the data:
?>
[/php]
You have selected icing for the cake.
2.render() : render(string $action, string $layout, string $file)
The render() method is automatically called at the end of each requested controller action. This method performs all the view logic (using the data you’ve given in using the set() method), places the view inside its layout and serves it back to the end user.
[php]
class RecipesController extends AppController
{
function search()
{
// Render the view in /views/recipes/search.ctp
$this->render();
}
}
[/php]
In your controller you may want to render a different view than what would conventionally be done. You can do this by calling render() directly.
[php]
class PostsController extends AppController
{
function my_action()
{
$this->render(‘custom_file’);
}
}
[/php]
3.redirect() : redirect(mixed $url, integer $status, boolean $exit)
Redirect() is a flow control method. This method takes its first parameter in the form of a CakePHP-relative URL.
[php]
function placeOrder()
{
//Logic for finalizing order goes here
if($success)
{
$this->redirect(array(‘controller’ => ‘orders’, ‘action’ => ‘thanks’));
}
else
{
$this->redirect(array(‘controller’ => ‘orders’, ‘action’ => ‘confirm’));
}
}
[/php]
You can also pass data to the action:
$this->redirect(array(‘action’ => ‘edit’, $id));
4.flash() : flash(string $message, string $url, integer $pause, string $layout)
flash() method is used to direct a user to a new page after an operation. The flash() method is different in that it shows a message before passing the user on to another URL.The first parameter should hold the message to be displayed, and the second parameter is a CakePHP-relative URL. CakePHP will display the $message for $pause seconds before forwarding the user on.
3.4.2 Controller Callbacks
CakePHP controllers come fitted with callbacks you can use to insert logic just before or after controller actions are rendered.
- beforeFilter():This function is executed before every action in the controller.
- BeforeRender():This function Called after controller action logic, but before the view is rendered
- AfterFilter():Called after every controller action, and after rendering is complete. This is the last controller method to run.
- requestAction : requestAction(string $url, array $options)
- LoadModel : loadModel(string $modelClass, mixed $id)
This function calls a controller’s action from any location and returns data from the action. The $url passed is a CakePHP-relative URL (/controllername/actionname/params). To pass extra data to the receiving controller action add to the $options array.
The loadModel function comes handy when you need to use a model which is not the controller’s default model or its associated model.
$this->loadModel(‘Article’);
$recentArticles = $this->Article->find(‘all’, array(‘limit’ => 5, ‘order’ => ‘Article.created DESC’));
3.5 Components
A Component is a class that aids in controller logic. Components are packages of logic that are shared between controllers.
3.5.1 Creating Components
The first step is to create a new component file and class. Create the file in /app/controllers/components/math.php. The basic structure for the component would look something like this:
[php]
<?php
class MathComponent extends Object
{
function doComplexOperation($amount1, $amount2)
{
return $amount1 + $amount2;
}
}
?>
[/php]
3.5.2 Including Components in your Controllers
Once our component is finished, we can use it in the application’s controllers by placing the component’s name (minus the “Component” part) in the controller’s $components array. The controller will automatically be given a new attribute named after the component, through which we can access an instance of it:
var $components = array(‘Math’, ‘Session’);
3.5.3 Calling Component Methods
Once the component is included in Controller ,the controller methods are accessible as $this->Component->action();
$this->Math->doComplexOperation(5, 4);
3.6 Models
Models represent data and are used in CakePHP applications for data access. A model usually represents a database table .A model can be associated with other models. For example, a Recipe may be associated with the Author of the recipe as well as the Ingredient in the recipe.Some class names are not usable for model names. For instance “File” cannot be used as “File” is a class already existing in the CakePHP core.simple example of a model definition in CakePHP:
/app/models/ingredient.php.
[php]
<?php
class Ingredient extends AppModel {
var $name = ‘Ingredient’;
}
?>
[/php]
The $name property is necessary for PHP4 but optional for PHP5.
[php]
<?php
class IngredientsController extends AppController {
function index() {
//grab all ingredients and pass it to the view:
$ingredients = $this->Ingredient->find(‘all’);
$this->set(‘ingredients’, $ingredients);
}
}
?>
[/php]
3.6.1 Retrieving Data
3.6.1.1.find :find($type, $params)
Find is the multifunctional workhorse of all model data-retrieval functions. $type can be either ‘all’, ‘first’, ‘count’, ‘list’, ‘neighbors’ or ‘threaded’. The default find type is ‘first’. Keep in mind that $type is case sensitive. Using a upper case character (for example ‘All’) will not produce the expected results.$params is used to pass all parameters to the various finds, and has the following possible keys by default – all of which are optional:
array(
‘conditions’ => array(‘Model.field’ => $thisValue), //array of conditions
‘recursive’ => 1, //int
‘fields’ => array(‘Model.field1’, ‘DISTINCT Model.field2’), //array of field names
‘order’ => array(‘Model.created’, ‘Model.field3 DESC’), //string or array defining order
‘group’ => array(‘Model.field’), //fields to GROUP BY
‘limit’ => n, //int
‘page’ => n, //int
‘offset’=>n, //int
‘callbacks’ => true //other possible values are false, ‘before’, ‘after’
)
simple (controller code) examples :find(‘first’),find(‘list’),find(‘all’) and find(‘neighbors’)
function some_function()
{
$semiRandomArticle = $this->Article->find();
$alsoLastCreated = $this->Article->find(‘first’, array(‘order’ => array(‘Article.created DESC’)));
$publishedAuthors = $this->Article->find(‘count’, array(
‘fields’ => ‘DISTINCT Article.user_id’,
‘conditions’ => array(‘Article.status ! =’ => ‘pending’)
));
$allAuthors = $this->Article->User->find(‘all’);
$allPublishedAuthors = $this->Article->find(‘list’, array(
‘fields’ => array(‘User.id’, ‘User.name’),
‘conditions’ => array(‘Article.status !=’ => ‘pending’),
‘recursive’ => 0));
$neighbors = $this->Article->find(‘neighbors’, array(‘field’ => ‘id’, ‘value’ => 3));
}
3.6.1.2.query : query(string $query)
query() uses the table name in the query as the array key for the returned data, rather than the model name. For example,
$this->Picture->query(“SELECT * FROM pictures LIMIT 2;”);
3.6.1.3.field : field(string $name, array $conditions = null, string $order = null)
Returns the value of a single field, specified as $name, from the first record matched by $conditions as ordered by $order. If no conditions are passed and the model id is set, will return the field value for the current model result. If no matching record is found returns false.$fields is used to pass a single field name, as a string, or an array of field names; if left empty, all fields will be fetched.
$this->Post->id = 22;
echo $this->Post->field(‘name’); // echo the name for row id 22
echo $this->Post->field(‘name’, array(‘created <‘ => date(‘Y-m-d H:i:s’)), ‘created DESC’);
// echo the name of the last created instance
3.6.1.4.read()
read() is a method used to set the current model data (Model::$data)–such as during edits–but it can also be used in other circumstances to retrieve a single record from the database.
function beforeDelete($cascade) {
…
$rating = $this->read(‘rating’); // gets the rating of the record being deleted.
$name = $this->read(‘name’, $id2); // gets the name of a second record.
$rating = $this->read(‘rating’); // gets the rating of the second record.
$this->id = $id3; //
$this->Article->read(); // reads a third record
$record = $this->data // stores the third record in $record
…
}
3.6.1.5 Saving Data
CakePHP makes saving model data a snap. Data ready to be saved should be passed to the model’s save() method.
3.6.1.6 Data Validation
Data validation is an important part of any application, as it helps to make sure that the data in a Model conforms to the business rules of the application.The first step to data validation is creating the validation rules in the Model. To do that, use the Model.
[php]
<?php
class User extends AppModel {
var $name = ‘User’;
var $validate = array(
‘login’ => ‘alphaNumeric’,
’email’ => ’email’,
‘born’ => ‘date’
);
}
?>
[/php]
where ‘login’,’email’,’born’ represents the field names and ‘alphaNumeric’,’email’,’date’.For the login field, only letters and numbers will be accepted, the email should be valid, and born should be a valid date. Multiples rules can be specified for a single field.
[php]
<?php
class User extends AppModel {
var $name = ‘User’;
var $validate = array(
‘login’ => array (
‘alphaNumeric’ => array(
‘rule’ => ‘alphaNumeric’,
‘required’ => true,
‘message’ => ‘Alphabets and numbers only’
),
‘between’ => array(
‘rule’ => array(‘between’, 5, 15),
‘message’ => ‘Between 5 to 15 characters’
)
),
‘password’ =>array(
‘rule’ => array(‘minLength’, ‘8’),
‘message’ => ‘Mimimum 8 characters long’
),
’email’ => ’email’,
‘born’ => array(
‘rule’ => ‘date’,
‘message’ => ‘Enter a valid date’,
‘allowEmpty’ => true
)
);
}
?>
[/php]
Two validation rules are defined for login: it should contain letters and numbers only, and its length should be between 5 and 15. The password field should be a minimum of 8 characters long. The email should be a valid email address, and born should be a valid date.CakePHP will use specified error messages when these validation rules fail.
4 Comments