Cakephp Tutorial
Cakephp Tutorial
CakePHP is based on an MVC-like architecture that is both powerful and easy to grasp.
Models, Views, and Controllers guarantee a strict but natural separation of business logic
from data and presentation layers.
Audience
This tutorial is meant for web developers and students who would like to learn how to
develop websites using CakePHP. It will provide a good understanding of how to use this
framework.
Prerequisites
Before you proceed with this tutorial, we assume that you have knowledge of HTML, Core
PHP, and Advance PHP. We have used CakePHP version 3.2.7 in all the examples.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
CakePHP
Table of Contents
About the Tutorial .................................................................................................................................. i
Audience ................................................................................................................................................ i
Prerequisites .......................................................................................................................................... i
Connecting Routes............................................................................................................................... 11
9. CAKEPHP — CONTROLLERS............................................................................................. 20
AppController ...................................................................................................................................... 20
Controller Actions................................................................................................................................ 21
ii
CakePHP
Redirecting .......................................................................................................................................... 21
Authentication .................................................................................................................................... 47
Email ................................................................................................................................................... 68
iii
CakePHP
Write Cookie........................................................................................................................................ 80
CSRF .................................................................................................................................................... 86
iv
1. CakePHP — Overview CakePHP
Open Source
MVC Framework
Templating Engine
Caching Operations
Built-in Validation
Localization
1
CakePHP
A typical CakePHP request cycle starts with a user requesting a page or resource in your
application. At a high level, each request goes through the following steps:
Any dispatch filters that are configured can handle the request, and optionally
generate a response.
The dispatcher selects the appropriate controller & action based on routing rules.
The controller’s action is called and the controller interacts with the required Models
and Components.
The controller delegates response creation to the View to generate the output
resulting from the model data.
The view uses Helpers and Cells to generate the response body and headers.
2
2. CakePHP — Installation CakePHP
Installing CakePHP is simple and easy. You can install it from composer or you can
download it from github — https://github.com/cakephp/cakephp/releases. We will further
understand how to install CakePHP in WampServer. After downloading it from github,
extract all the files in a folder called “CakePHP” in WampServer. You can give custom name
to folder but we have used “CakePHP”.
Make sure that the directories logs, tmp and all its subdirectories have write permission
as CakePHP uses these directories for various operations.
After extracting it, let’s check whether it has been installed correctly or not by visiting the
following URL in browser: http://localhost:85/CakePHP/
The above URL will direct you to the screen as shown below. This shows that CakePHP has
successfully been installed.
3
3. CakePHP — Folder Structure CakePHP
Take a look at the following screenshot. It shows the folder structure of CakePHP.
Folder
Description
Name
The config folder holds the (few) configuration files CakePHP uses.
config Database connection details, bootstrapping, core configuration files and
more should be stored here.
The logs folder normally contains your log files, depending on your log
logs
configuration.
plugins The plugins folder is where the Plugins your application uses are stored.
The src folder will be where you work your magic: It is where your
application’s files will be placed. CakePHP’s src folder is where you will
do most of your application development. Let’s look a little closer at the
folders inside src.
src Console Contains the console commands and console tasks for
your application.
4
CakePHP
tests The tests folder will be where you put the test cases for your application.
The tmp folder is where CakePHP stores temporary data. The actual data
it stores depends on how you have CakePHP configured, but this folder
tmp
is usually used to store model descriptions and sometimes session
information.
5
4. CakePHP — Configuration CakePHP
CakePHP comes with one configuration file by default and we can modify it according to
our needs. There is one dedicated folder “config” for this purpose. CakePHP comes with
different configuration options.
General Configuration
The following table describes the role of various variables and how they affect your
CakePHP application.
The base directory the app resides in. If false, this will be auto
App.base
detected.
6
CakePHP
Databases Configuration
Database can be configured in config/app.php file. This file contains a default connection
with provided parameters which can be modified as per our choice. The below screenshot
shows the default parameters and values which should be modified as per the requirement.
Key Description
The fully namespaced class name of the class that represents the
connection to a database server. This class is responsible for
className
loading the database driver, providing SQL transaction
mechanisms and preparing SQL statements among other things.
7
CakePHP
port (optional) The TCP port or Unix socket used to connect to the server.
ssl_key The file path to the SSL key file. (Only supported by MySQL).
8
5. CakePHP — Email Configuration CakePHP
You can add custom transports (or override existing transports) by adding the appropriate
file to src/Mailer/Transport. Transports should be named YourTransport.php, where
'Your' is the name of the transport. Following is the example of Email configuration
transport.
Example
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
9
CakePHP
Example
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you@localhost',
],
],
10
6. CakePHP — Routing CakePHP
Routing maps your URL to specific controller’s action. In this section, we will see how you
can implement routes, how you can pass arguments from URL to controller’s action, how
you can generate URLs, and how you can redirect to a specific URL. Normally, routes are
implemented in file config/routes.php. Routing can be implemented in two ways:
static method
scoped route builder
Both the methods will execute the index method of ArticlesController. Out of the two
methods scoped route builder gives better performance.
Connecting Routes
Router::connect() method is used to connect routes. The following is the syntax of the
method:
The first argument is for the URL template you wish to match.
The second argument contains default values for your route elements.
The third argument contains options for the route which generally contains regular
expression rules.
11
CakePHP
$routes->connect(
'URL template',
['default' => 'defaultValue'],
['option' => 'matchingRegex']
);
Example
Make changes in the config/routes.php file as shown below.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/TestsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
class TestsController extends AppController{
12
CakePHP
}
}
?>
Create a folder Tests under src/Template and under that folder create a View file called
index.ctp. Copy the following code in that file.
src/Template/Tests/index.ctp
http://localhost:85/CakePHP/
Passed Arguments
Passed arguments are the arguments which are passed in the URL. These arguments can
be passed to controller’s action. These passed arguments are given to your controller in
three ways.
13
CakePHP
Here the value1 from URL will be assigned to arg1 and value2 will be assigned to arg2.
$args = $this->request->params[‘pass’]
The above statement will pass two arguments 5, and 6 to TestController’s index()
method.
Example
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action'
=> 'index'],['pass' => ['arg1', 'arg2']]);
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' =>
'display']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
14
CakePHP
src/Controller/TestsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
Create a folder Tests at src/Template and under that folder create a View file called
index.ctp. Copy the following code in that file.
src/Template/Tests/index.ctp
http://localhost:85/CakePHP/tests/Virat/Kunal
Upon execution, the above URL will produce the following output.
15
7. CakePHP — Generating URLs CakePHP
This is a cool feature of CakePHP. Using the generated URLs, we can easily change the
structure of URL in the application without modifying the whole code.
If true, the full base URL will be prepended to the result. Default is false.
Example
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes-
>connect('/generate',['controller'=>'Generates','action'=>'index']);
});
Plugin::routes();
src/Controller/GeneratesController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
16
CakePHP
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
}
}
?>
Create a folder Generates at src/Template and under that folder create a View file
called index.ctp. Copy the following code in that file.
src/Template/Generates/index.ctp
http://localhost:85/CakePHP/generate
17
8. CakePHP — Redirect Routing CakePHP
Redirect routing is useful when we want to inform client applications that this URL has
been moved. The URL can be redirected using the following function.
An array matching the named elements in the route to regular expressions which
that element should match.
Example
Make Changes in the config/routes.php file as shown below. Here, we have used
controllers that were created previously.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
Plugin::routes();
18
CakePHP
URL 1 — http://localhost:85/CakePHP/generate_url
URL 2 — http://localhost:85/CakePHP/generate1
URL 3 — http://localhost:85/CakePHP/generate2
19
9. CakePHP — Controllers CakePHP
The controller as the name indicates controls the application. It acts like a bridge between
models and views. Controllers handle request data, makes sure that correct models are
called and right response or view is rendered. Methods in the controllers’ class are called
actions. Each controller follows naming conventions. The Controller class names are in
plural form, Camel Cased, and end in Controller — PostsController.
AppController
The AppConttroller class is the parent class of all applications’ controllers. This class
extends the Controller class of CakePHP. AppController is defined at
src/Controller/AppController.php. The file contains the following code.
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', application/xml'])
) {
$this->set('_serialize', true);
}
}
}
20
CakePHP
AppController can be used to load components that will be used in every controller of
your application. The attributes and methods created in AppController will be available in
all controllers that extend it. The initialize() method will be invoked at the end of
controller’s constructor to load components.
Controller Actions
The methods in the controller class are called Actions. Actions are responsible for sending
appropriate response for browser/user making the request. View is rendered by the name
of action, i.e., the name of method in controller.
Example
As you can see in the above example, the RecipesController has 3 actions — View,
Share, and Search.
Redirecting
For redirecting a user to another action of the same controller, we can use the setAction()
method. The following is the syntax for the setAction() method:
Cake\Controller\Controller::setAction($action, $args...)
The following code will redirect the user to index action of the same controller.
$this->setAction('index');
21
CakePHP
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/redirect-
controller',['controller'=>'Redirects','action'=>'action1']);
$routes->connect('/redirect-
controller2',['controller'=>'Redirects','action'=>'action2']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/RedirectsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
22
CakePHP
Create a directory Redirects at src/Template and under that directory create a View
file called action1.ctp. Copy the following code in that file.
src/Template/Redirects/action1.ctp
http://localhost:85/CakePHP/redirect-controller
Output
Upon execution, you will receive the following output.
Now, vist
23
CakePHP
Loading Models
In CakePHP, a model can be loaded using the loadModel() method. The following is the
syntax for the loadModel() method.
Example
If you want to load Articles model in a controller, then it can be loaded by writing the
following line in controller’s action.
$this->loadModel('Articles');
24
10. CakePHP — Views CakePHP
The letter “V” in the MVC is for Views. Views are responsible for sending output to user
based on request. View Classes is a powerful way to speed up the development process.
View Templates
The View Templates file of CakePHP has default extension .ctp (CakePHP Template). These
templates get data from controller and then render the output so that it can be displayed
properly to the user. We can use variables, various control structures in template.
Template files are stored in src/Template/, in a directory named after the controller that
uses the files, and named after the action it corresponds to. For example, the View file
for the Products controller’s “view()” action, would normally be found in
src/Template/Products/view.ctp.
In short, the name of the controller (ProductsController) is same as the name of the folder
(Products) but without the word Controller and name of action/method (view()) of the
controller (ProductsController) is same as the name of the View file(view.ctp).
View Variables
View variables are variables which get the value from controller. We can use as many
variables in view templates as we want. We can use the set() method to pass values to
variables in views. These set variables will be available in both the view and the layout
your action renders. The following is the syntax of the set() method.
This method takes two arguments — the name of the variable and its value.
Example
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
25
CakePHP
$routes->connect('template',['controller'=>'Products','action'=>'view']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/ProductsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
Create a directory Products at src/Template and under that folder create a View file
called view.ctp. Copy the following code in that file.
src/Template/Products/view.ctp
http://localhost:85/CakePHP/template
26
CakePHP
Output
The above URL will produce the following output.
27
11. CakePHP — Extending Views CakePHP
Many times, while making web pages, we want to repeat certain part of pages in other
pages. CakePHP has such facility by which one can extend view in another view and for
this, we need not repeat the code again. The extend() method is used to extend views in
View file. This method takes one argument, i.e., the name of the view file with path. Don’t
use extension .ctp while providing the name of the View file.
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('extend',['controller'=>'Extends','action'=>'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/ExtendsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
28
CakePHP
}
}
?>
Create a directory Extends at src/Template and under that folder create a View file
called header.ctp. Copy the following code in that file.
src/Template/Extends/header.ctp
<div align="center">
<h1>Common Header</h1>
</div>
<?= $this->fetch('content') ?>
Create another View under Extends directory called index.ctp. Copy the following code
in that file. Here we are extending the above view header.ctp.
src/Template/Extends/index.ctp
http://localhost:85/CakePHP/extend
Output
Upon execution, you will receive the following output.
29
12. CakePHP ─ View Elements CakePHP
Certain parts of the web pages are repeated on multiple web pages but at different
locations. CakePHP can help us reuse these repeated parts. These reusable parts are called
Elements — help box, extra menu etc. An element is basically a mini-view. We can
also pass variables in elements.
The second argument is the array of data to be made available to the rendered
view.
Out of the 3 arguments, the first one is compulsory while, the rest are optional.
Example
Create an element file at src/Template/Element directory called helloworld.ctp. Copy
the following code in that file.
src/Template/Element/helloworld.ctp
<p>Hello World</p>
Create a folder Elems at src/Template and under that directory create a View file called
index.ctp. Copy the following code in that file.
src/Template/Elems/index.ctp
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
30
CakePHP
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/element-
example',['controller'=>'Elems','action'=>'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/ElemsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
}
}
?>
http://localhost:85/CakePHP/element-example
31
CakePHP
Output
Upon execution, the above URL will give you the following output.
32
13. CakePHP ─ View Events CakePHP
There are several callbacks/events that we can use with View Events. These events are
helpful to perform several tasks before something happens or after something happens.
The following is a list of callbacks that can be used with CakePHP.
33
14. CakePHP — Working with Database CakePHP
Working with database in CakePHP is very easy. We will understand the CRUD (Create,
Read, Update, Delete) operations in this chapter. Before we proceed, we need to create
the following users’ table in the database.
Insert a Record
To insert a record in database, we first need to get hold of a table using TableRegistry
class. We can fetch the instance out of registry using get() method. The get() method
will take the name of the database table as an argument.
This new instance is used to create new entity. Set necessary values with the instance of
new entity. We now have to call the save() method with TableRegistry class’s instance
which will insert new record in database.
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
34
CakePHP
src/controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Auth\DefaultPasswordHasher;
Create a directory Users at src/Template and under that directory create a View file
called add.ctp. Copy the following code in that file.
src/Template/Users/add.ctp
<?php
echo $this->Form->create("Users",array('url'=>'/users/add'));
echo $this->Form->input('username');
echo $this->Form->input('password');
35
CakePHP
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
http://localhost:85/CakePHP/users/add
Output
Upon execution, you will receive the following output.
36
15. CakePHP ─ View a Record CakePHP
To view records of database, we first need to get hold of a table using the TableRegistry
class. We can fetch the instance out of registry using get() method. The get() method
will take the name of the database table as argument. Now, this new instance is used to
find records from database using find() method. This method will return all records from
the requested table.
Example
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
src/controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
37
CakePHP
Create a directory Users at src/Template, ignore if already created, and under that
directory create a View file called index.ctp. Copy the following code in that file.
src/Template/Users/index.ctp
38
CakePHP
http://localhost:85/CakePHP/users
Output
Upon execution, the above URL will give you the following output.
39
16. CakePHP — Update a Record CakePHP
To update a record in database we first need to get hold of a table using TableRegistry
class. We can fetch the instance out of registry using the get() method. The get() method
will take the name of the database table as an argument. Now, this new instance is used
to get particular record that we want to update.
Call the get() method with this new instance and pass the primary key to find a record
which will be saved in another instance. Use this instance to set new values that you want
to update and then finally call the save() method with the TableRegistry class’s instance
to update record.
Example
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
src/controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
40
CakePHP
use Cake\Datasource\ConnectionManager;
if($this->request->is('post')){
$username = $this->request->data('username');
$password = $this->request->data('password');
$users_table = TableRegistry::get('users');
$users = $users_table->get($id);
$users->username = $username;
$users->password = $password;
if($users_table->save($users))
echo "User is udpated";
$this->setAction('index');
}else{
$users_table = TableRegistry::get('users')->find();
$users = $users_table->where(['id'=>$id])->first();
$this->set('username',$users->username);
$this->set('password',$users->password);
$this->set('id',$id);
}
}
}
?>
41
CakePHP
Create a directory Users at src/Template, ignore if already created, and under that
directory create a view called index.ctp. Copy the following code in that file.
src/Template/Users/index.ctp
Create another View file under the Users directory called edit.ctp and copy the following
code in it.
src/Template/Users/edit.ctp
<?php
echo $this->Form->create("Users",array('url'=>'/users/edit/'.$id));
echo $this->Form->input('username',['value'=>$username]);
echo $this->Form->input('password',['value'=>$password]);
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
42
CakePHP
Execute the above example by visiting the following URL and click on Edit link to edit
record.
http://localhost:85/CakePHP/users
Output
After visiting the above URL and clicking on the Edit link, you will receive the following
output where you can edit record.
43
17. CakePHP ─ Delete a Record CakePHP
To delete a record in database, we first need to get hold of a table using the TableRegistry
class. We can fetch the instance out of registry using the get() method. The get() method
will take the name of the database table as an argument. Now, this new instance is used
to get particular record that we want to delete.
Call the get() method with this new instance and pass the primary key to find a record
which will be saved in another instance. Use the TableRegistry class’s instance to call the
delete method to delete record from database.
Example
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
src/controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
44
CakePHP
use Cake\Datasource\ConnectionManager;
Just create an empty View file under Users directory called delete.ctp.
src/Template/Users/delete.ctp
Create a directory Users at src/Template, ignore if already created, and under that
directory create a View file called index.ctp. Copy the following code in that file.
src/Template/Users/index.ctp
45
CakePHP
echo "<tr><td>".$row->id."</td>";
echo "<td>".$row->username."</td>";
echo "<td>".$row->password."</td>";
echo "<td><a href='".$this->Url->build(["controller" => "Users","action"
=> "edit",$row->id])."'>Edit</a></td>";
echo "<td><a href='".$this->Url->build(["controller" => "Users","action"
=> "delete",$row->id])."'>Delete</a></td></tr>";
endforeach;
?>
</table>
Execute the above example by visiting the following URL and click on Delete link to delete
record.
http://localhost:85/CakePHP/users
Output
After visiting the above URL and clicking on the Delete link, you will receive the following
output where you can delete record.
46
18. CakePHP — Services CakePHP
Authentication
Authentication is the process of identifying the correct user. CakePHP supports three types
of authentication.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/auth',['controller'=>'Authexs','action'=>'index']);
$routes->connect('/login',['controller'=>'Authexs','action'=>'login']);
$routes->connect('/logout',['controller'=>'Authexs','action'=>'logout']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
47
CakePHP
src/Controller/AppController.php
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Controller\Component\AuthComponent;
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Authexs',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Authexs',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Authexs',
'action' => 'login'
]
48
CakePHP
]);
$this->Auth->config('authenticate', [
AuthComponent::ALL => ['userModel' => 'users'],
'Form'
]);
}
src/Controller/AuthexsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Event\Event;
use Cake\Auth\DefaultPasswordHasher;
49
CakePHP
Create a directory Authexs at src/Template and under that directory create a View file
called login.ctp. Copy the following code in that file.
src/Template/Authexs/login.ctp
<?php
echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
Create another View file called logout.ctp. Copy the following code in that file.
src/Template/Authexs/logout.ctp
50
CakePHP
Create another View file called index.ctp. Copy the following code in that file.
src/Template/Authexs/index.ctp
http://localhost:85/CakePHP/auth
Output
As the authentication has been implemented so once you try to visit the above URL, you
will be redirected to the login page as shown below.
After providing the correct credentials, you will be logged in and redirected to the screen
as shown below.
After clicking on the logout link, you will be redirected to the login screen again.
51
19. CakePHP — Errors & Exception Handling CakePHP
Failure of system needs to be handled effectively for smooth running of the system.
CakePHP comes with default error trapping that prints and logs error as they occur. This
same error handler is used to catch Exceptions. Error handler displays errors when debug
is true and logs error when debug is false. CakePHP has number of exception classes and
the built in exception handling will capture any uncaught exception and render a useful
page.
52
CakePHP
Example
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes-
>connect('/exception/:arg1/:arg2',['controller'=>'Exps','action'=>'index'],['pa
ss' => ['arg1', 'arg2']]);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/ExpsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Core\Exception\Exception;
53
CakePHP
}catch(\Exception $ex){
echo $ex->getMessage();
}
}
}
?>
Create a directory Exps at src/Template and under that directory create a View file
called index.ctp. Copy the following code in that file.
src/Template/Exps/index.ctp
http://localhost:85/CakePHP/exception/5/0
Output
Upon execution, you will receive the following output.
54
20. CakePHP — Logging CakePHP
Logging in CakePHP is a very easy task. You just have to use one function. You can log
errors, exceptions, user activities, action taken by users, for any background
process like cronjob. Logging data in CakePHP is easy - the log() function is provided by
the LogTrait, which is the common ancestor for almost all CakePHP classes.
Logging Configuration
We can configure the log in file config/app.php. There is a log section in the file where
you can configure logging options as shown in the following screenshot.
By default, you will see two log levels — error and debug already configured for you.
Each will handle different level of messages.
55
CakePHP
The first is to use the static write() method. The following is the syntax of the static
write() method .
The severity level of the message being written. The value must be an
integer or string matching a known level.
Parameters Additional data to be used for logging the message. The special scope
key can be passed to be used for further filtering of the log engines to
be used. If a string or a numerically index array is passed, it will be
treated as the scope key. See Cake\Log\Log::config() for more
information on logging scopes.
Returns boolean
Writes the given message and type to all of the configured log
Description adapters. Configured adapters are passed both the $level and
$message variables. $level is one of the following strings/values.
The second is to use the log() shortcut function available on any using the LogTrait
Calling log() will internally call Log::write():
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('logex',['controller'=>'Logexs','action'=>'index']);
56
CakePHP
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/LogexController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Log\Log;
Create a directory Logexs at src/Template and under that directory create a View file
called index.ctp. Copy the following code in that file.
src/Template/Logexs/index.ctp
http://localhost:85/CakePHP/logex
57
CakePHP
Output
Upon execution, you will receive the following output.
58
21. CakePHP — Form Handling CakePHP
CakePHP provides various in built tags to handle HTML forms easily and securely. Like
many other PHP frameworks, major elements of HTML are also generated using CakePHP.
Following are the various functions used to generate HTML elements.
Elements to format
HTML attributes
Returns array
59
CakePHP
The model name for which the form is being defined. Should
include the plugin name for plugin models. e.g.
ContactManager.Contact. If an array is passed and $options
argument is empty, the array will be used as options. If false no
Parameters
model is used.
The following functions are used to provide file uploading functionality on HTML page.
60
CakePHP
The following functions are used to create hidden element on HTML page.
The following functions are used to generate input element on HTML page.
Description Generates a form input element complete with label and wrapper div
The following functions are used to generate radio button on HTML page.
The following functions are used to generate submit button on HTML page.
Array of options. Possible options are div, before, after, type etc.
61
CakePHP
The following functions are used to generate textarea element on HTML page.
Example
Make changes in the config/routes.php file as shown in the following code.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes-
>connect('register',['controller'=>'Registrations','action'=>'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
62
CakePHP
src/Controller/RegistrationController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
src/Template/Registrations/index.ctp
<?php
echo $this->Form->create("Registrations",array('url'=>'/register'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('password');
echo '<label for="country">Country</label>';
echo $this->Form->select('country',$country);
echo '<label for="gender">Gender</label>';
echo $this->Form->radio('gender',$gender);
echo '<label for="address">Address</label>';
echo $this->Form->textarea('address');
echo $this->Form->file('profilepic');
echo '<div>'.$this->Form->checkbox('terms').'<label for="country">Terms &
Conditions</label></div>';
echo $this->Form->button('Submit');
63
CakePHP
echo $this->Form->end();
?>
Output
Upon execution, you will receive the following output.
64
22. CakePHP — Internationalization CakePHP
Step 2: Create subdirectory for each language under the directory src\Locale. The name
of the subdirectory can be two letter ISO code of the language or full locale name like
en_US, fr_FR etc.
Step 3: Create separate default.po file under each language subdirectory. This file
contains entry in the form of msgid and msgstr as shown in the following program.
msgid "msg"
msgstr "CakePHP Internationalization example."
Here, the msgid is the key which will be used in the View template file and msgstr is the
value which stores the translation.
Step 4: In the View template file, we can use the above msgid as shown below which will
be translated based on the set value of locale.
The default locale can be set in the config/bootstrap.php file by the following line.
use Cake\I18n\I18n;
I18n::locale('de_DE');
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
65
CakePHP
Router::defaultRouteClass('DashedRoute');
$routes-
>connect('locale',['controller'=>'Localizations','action'=>'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/LocalizationsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\I18n\I18n;
66
CakePHP
src/Locale/en_US/default.po
msgid "msg"
msgstr "CakePHP Internationalization example."
src/Locale/fr_FR/default.po
msgid "msg"
msgstr "Exemple CakePHP internationalisation."
src/Locale/de_DE/default.po
msgid "msg"
msgstr "CakePHP Internationalisierung Beispiel."
src/Template/Localizations/index.ctp
<?php
echo $this->Form->create("Localizations",array('url'=>'/locale'));
echo $this->Form->radio("locale",
[
['value'=>'en_US','text'=>'English'],
['value'=>'de_DE','text'=>'German'],
['value'=>'fr_FR','text'=>'French'],
]
);
echo $this->Form->button('Change Language');
echo $this->Form->end();
?>
<?php echo __('msg'); ?>
http://localhost:85/CakePHP/locale
67
CakePHP
Output
Upon execution, you will receive the following output.
Email
CakePHP provides Email class to manage email related functionalities. To use email
functionality in any controller, we first need to load the Email class by writing the following
line.
use Cake\Mailer\Email;
The Email class provides various useful methods which are described below.
Returns array|$this
Description It specifies from which email address; the email will be sent
Returns array|$this
68
CakePHP
Returns array
Description Send an email using the specified content, template and layout
Returns array|$this
Returns array|$this
Returns array|$this
Description Bcc
Returns array|$this
Description Cc
69
CakePHP
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/email',['controller'=>'Emails','action'=>'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/EmailsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Mailer\Email;
70
CakePHP
Create a directory Emails at src/Template and under that directory create a View file
called index.ctp. Copy the following code in that file.
src/Template/Emails/index.ctp
Email Sent.
Before we send any email, we need to configure it. In the below screenshot, you can see
that there are two transports, default and Gmail. We have used Gmail transport. You need
to replace the “GMAIL USERNAME” with your Gmail username and “APP PASSWORD” with
your applications password. You need to turn on 2-step verification in Gmail and create a
new APP password to send email.
config/app.php
71
CakePHP
Output
Upon execution, you will receive the following output.
72
23. CakePHP — Session Management CakePHP
Session allows us to manage unique users across requests and stores data for specific
users. Session data can be accessible anywhere anyplace where you have access to
request object, i.e., sessions are accessible from controllers, views, helpers, cells, and
components.
$session = $this->request->session();
Session::write($key, $value)
The above method will take two arguments, the value and the key under which the value
will be stored.
Example
$session->write('name', 'Virat Gandhi');
Session::read($key)
The above function will take only one argument that is the key of the value which was
used at the time of writing session data. Once the correct key was provided then the
function will return its value.
Example
$session->read('name');
When you want to check whether particular data exists in the session or not, then you can
use the check() session method.
Session::check($key)
73
CakePHP
Example
if ($session->check('name')) {
// name exists and is not null.
}
Session::delete($key)
The above function will take only key of the value to be deleted from session.
Example
$session->delete('name');
When you want to read and then delete data from session then, we can use the
consume() session method.
static Session::consume($key)
Example
$session->consume('name');
Destroying a Session
We need to destroy a user session when the user logs out from the site and to destroy the
session the destroy() method is used.
Session::destroy()
Example
$session->destroy();
74
CakePHP
Destroying session will remove all session data from server but will not remove session
cookie.
Renew a Session
In a situation where you want to renew user session then we can use the renew() session
method.
Session::renew()
Example
$session->renew();
Complete Session
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/session-
object',['controller'=>'Sessions','action'=>'index']);
$routes->connect('/session-
read',['controller'=>'Sessions','action'=>'retrieve_session_data']);
$routes->connect('/session-
write',['controller'=>'Sessions','action'=>'write_session_data']);
$routes->connect('/session-
check',['controller'=>'Sessions','action'=>'check_session_data']);
$routes->connect('/session-
delete',['controller'=>'Sessions','action'=>'delete_session_data']);
$routes->connect('/session-
destroy',['controller'=>'Sessions','action'=>'destroy_session_data']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
75
CakePHP
src/Controller/SessionsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
76
CakePHP
Create a directory Sessions at src/Template and under that directory create a View file
called write_session_data.ctp. Copy the following code in that file.
src/Template/Sessions/write_session_data.ctp
Create another View file called retrieve_session_data.ctp under the same Sessions
directory and copy the following code in that file.
src/Template/Sessions/retrieve_session_data.ctp
Create another View file called check_session_data.ctp under the same Sessions
directory and copy the following code in that file.
src/Template/Sessions/check_session_data.ctp
Create another View file called delete_session_data.ctp under the same Sessions
directory and copy the following code in that file.
src/Template/Sessions/delete_session_data.ctp
77
CakePHP
Create another View file called destroy_session_data.ctp under the same Sessions
directory and copy the following code in that file.
src/Template/Sessions/destroy_session_data.ctp
Session Destroyed.
Output
Execute the above example by visiting the following URL. This URL will help you write data
in session.
http://localhost:85/CakePHP/session-write
78
CakePHP
79
24. CakePHP — Cookie Management CakePHP
Handling Cookie with CakePHP is easy and secure. There is a CookieComponent class which
is used for managing Cookie. The class provides several methods for working with Cookies.
Write Cookie
The write() method is used to write cookie. Following is the syntax of the write() method.
The write() method will take two arguments, the name of cookie variable ($key), and
the value of cookie variable ($value).
Example
$this->Cookie->write('name', 'Virat');
Read Cookie
The read() method is used to read cookie. Following is the syntax of the read() method.
The read() method will take one argument, the name of cookie variable ($key).
Example
echo $this->Cookie->read('name');
Check Cookie
The check() method is used to check whether a key/path exists and has a non-null value.
Following is the syntax of the check() method.
Cake\Controller\Component\CookieComponent::check($key)
80
CakePHP
Example
echo $this->Cookie->check(‘name’);
Delete Cookie
The delete() method is used to delete cookie. Following is the syntax of the delete()
method.
Cake\Controller\Component\CookieComponent::delete(mixed $key)
The delete() method will take one argument, the name of cookie variable ($key) to delete.
Example 1
$this->Cookie->delete('name');
Example 2
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes-
>connect('cookie/write',['controller'=>'Cookies','action'=>'write_cookie']);
$routes-
>connect('cookie/read',['controller'=>'Cookies','action'=>'read_cookie']);
$routes-
>connect('cookie/check',['controller'=>'Cookies','action'=>'check_cookie']);
$routes-
>connect('cookie/delete',['controller'=>'Cookies','action'=>'delete_cookie']);
$routes->fallbacks('DashedRoute');
});
81
CakePHP
Plugin::routes();
src/Controller/Cookies/CookiesController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Controller\Component\CookieComponent;
Create a directory Cookies at src/Template and under that directory create a View file
called write_cookie.ctp. Copy the following code in that file.
82
CakePHP
src/Template/Cookie/write_cookie.ctp
Create another View file called read_cookie.ctp under the same Cookies directory and
copy the following code in that file.
src/Template/Cookie/read_cookie.ctp
Create another View file called check_cookie.ctp under the same Cookies directory and
copy the following code in that file.
src/Template/Cookie/check_cookie.ctp
<?php
if($isPresent):
?>
The cookie is present.
<?php
else:
?>
The cookie isn't present.
<?php
endif;
?>
Create another View file called delete_cookie.ctp under the same Cookies directory and
copy the following code in that file.
src/Template/Cookie/delete_cookie.ctp
83
CakePHP
Output
Execute the above example by visiting the following URL:
http://localhost:85/CakePHP/cookie/write
84
CakePHP
85
25. CakePHP — Security CakePHP
Security is another important feature while building web applications. It assures the users
of the website that their data is secured. CakePHP provides some tools to secure your
application.
The encrypt method will take text and key as the argument to encrypt data and the return
value will be the encrypted value with HMAC checksum.
To hash a data hash() method is used. Following is the syntax of the hash() method.
CSRF
CSRF stands for Cross Site Request Forgery. By enabling the CSRF Component, you
get protection against attacks. CSRF is a common vulnerability in web applications. It
allows an attacker to capture and replay a previous request, and sometimes submit data
requests using image tags or resources on other domains. The CSRF can be enabled by
simply adding the CsrfComponent to your components array as shown below.
The CsrfComponent integrates seamlessly with FormHelper. Each time you create a form
with FormHelper, it will insert a hidden field containing the CSRF token.
While this is not recommended, you may want to disable the CsrfComponent on certain
requests. You can do so by using the controller’s event dispatcher, during the
beforeFilter() method.
86
CakePHP
Security Component
Security Component applies tighter security to your application. It provides methods for
various tasks like:
Example
Make changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('login',['controller'=>'Logins','action'=>'index']);
$routes->fallbacks('DashedRoute');
});
87
CakePHP
Plugin::routes();
src/Controller/LoginsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
}
}
?>
Create a directory Logins at src/Template and under that directory create a View file
called index.ctp. Copy the following code in that file.
src/Template/Logins/index.ctp
<?php
echo $this->Form->create("Logins",array('url'=>'/login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
88
CakePHP
Output
Upon execution, you will receive the following output.
89
26. CakePHP — Validation CakePHP
Often while making websites we need to validate certain things before processing data
further. CakePHP provides validation package to build validators that can validate data
with ease.
Validation Methods
CakePHP provides various validation methods in the Validation Class. Some of the most
popular of them are listed below.
The name of the field from which the rule will be added.
Returns $this
Returns $this
90
CakePHP
Returns $this
The type of cards you want to allow. Defaults to 'all'. You can also
supply an array of accepted card types, for example,
['mastercard', 'visa', 'amex'].
Parameters
Returns $this
Returns $this
91
CakePHP
Returns $this
Returns $this
Returns $this
92
27. CakePHP — Creating Validators CakePHP
Validator can be created by adding the following two lines in the controller.
use Cake\Validation\Validator;
$validator = new Validator();
Validating Data
Once we have created validator, we can use the validator object to validate data. The
following code explains how we can validate data for login webpage.
Using the $validator object we have first called the notEmpty() method which will ensure
that the username must not be empty. After that we have chained the add() method to
add one more validation for proper email format.
After that we have added validation for password field with notEmpty() method which will
confirms that password field must not be empty.
Example
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('validation',['controller'=>'Valids','action'=>'index']);
93
CakePHP
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
src/Controller/ValidsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Validation\Validator;
Create a directory Valids at src/Template and under that directory create a View file
called index.ctp. Copy the following code in that file.
src/Template/Valids/index.ctp
<?php
if($errors)
{
foreach($errors as $error)
foreach($error as $msg)
echo '<font color="red">'.$msg.'</font><br>';
94
CakePHP
}else{
echo "No errors.";
}
echo $this->Form->create("Logins",array('url'=>'/validation'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
http://localhost:85/CakePHP/validation
Output
Click on the submit button without entering anything. You will receive the following output.
95