How to Learn Tutorial in CakePHP

Learn Tutorial in CakePHP

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. 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.

How to Logging Configuration in CakePHP

Logging Configuration in 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.

Logging Configuration

By default, you will see two log levels − error and debug already configured for you. Each will handle different level of messages.

CakePHP supports various logging levels as shown below −

  • Emergency − System is unusable
  • Alert − Action must be taken immediately
  • Critical − Critical conditions
  • Error − Error conditions
  • Warning − Warning conditions
  • Notice − Normal but significant condition
  • Info − Informational messages
  • Debug − Debug-level messages

Writing to Log file

There are two ways by which we can write in a Log file.

The first is to use the static write() method. The following is the syntax of the static write() method .

Syntax write( integer|string $level , mixed $message , string|array $context[] )
Parameters The severity level of the message being written. The value must be an integer or string matching a known level.

Message content to log.

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 CakeLogLog::config() for more information on logging scopes.

Returns boolean
Description Writes the given message and type to all of the configured log 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 CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘logex’,[‘controller’=>’Logexs’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a LogexController.php file at src/Controller/LogexController.php. Copy the following code in the controller file.

src/Controller/LogexController.php

<?php namespace AppController; use AppControllerAppController; use CakeLogLog; class LogexsController extends AppController{ public function index(){ /*The first way to write to log file.*/ Log::write(‘debug’,”Something didn’t work.”); /*The second way to write to log file.*/ $this->log(“Something didn’t work.”,’debug’); } } ?>

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

Something is written in log file. Check log file logsdebug.log

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/logex

Output

Upon execution, you will receive the following output.

Logexs

How to Redirect Routing in CakePHP

Redirect Routing in CakePHP

Redirect url in cakephp is simple to do but important feature for development. 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.

static Cake\Routing\Router::redirect($route, $url, $options =[])

There are three arguments to the above function −

  • A string describing the template of the route.
  • A URL to redirect to.
  • 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) {
      $routes->connect('/generate2', ['controller' => 'Tests', 'action' => 'index']);
      $routes->redirect('/generate1','http://tutorialsbay.org/');
      $routes->connect('/generate_url',['controller'=>'Generates','action'=>'index']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

Execute the above example by visiting the following URLs.

  • URL 1 — http://localhost:85/CakePHP/generate_url
  • URL 2 — http://localhost:85/CakePHP/generate1
  • URL 3 — http://localhost:85/CakePHP/generate2

Output for URL 1

Output for URL 2

Output for URL 3

 

How to Route in CakePHP

Route in CakePHP

Routing in cakephp is an important issue about redirect URL. 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

Here is an example presenting both the types.

// Using the scoped route builder.
Router::scope('/', function ($routes) {
   $routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);
});

// Using the static method.
Router::connect('/', ['controller' => 'Articles', 'action' => 'index']);

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 −

static Cake\Routing\Router::connect($route, $defaults =[], $options =[])

There are three arguments to the Router::connect() 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.

Here is the basic format of a route −

$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->connect('/', ['controller' => 'Tests', 'action' => 'index']);
      $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

Create a TestsController.php file at src/Controller/TestsController.php. Copy the following code in the controller file.

src/Controller/TestsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;

   class TestsController extends AppController{
      public function index(){
      }
   }
?>

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

This is CakePHP tutorial and this is an example of connecting routes.

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/

The above URL will yield the following output.

Routing

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.

As arguments to the action method

Following example shows how we can pass arguments to the action of the controller.

Visit the following URL − http://localhost:85/CakePHP/tests/value1/value2

This will match the following route line.

$routes->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' =>
   'index'],['pass' => ['arg1', 'arg2']]);

Here the value1 from URL will be assigned to arg1 and value2 will be assigned to arg2.

As numerically indexed array

Once the argument is passed to the controller’s action, you can get the argument with the following statement.

$args = $this->request->params[‘pass’]

The arguments passed to controller’s action will be stored in $args variable.

Using routing array

The argument can also be passed to action by the following statement −

$routes->connect('/', ['controller' => 'Tests', 'action' => 'index',5,6]);

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();

Create a TestsController.php file at src/Controller/TestsController.php. Copy the following code in the controller file.

src/Controller/TestsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;

   class TestsController extends AppController{
      public function index($arg1,$arg2){
         $this->set('argument1',$arg1);
         $this->set('argument2',$arg2);
      }
   }
?>

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

This is CakePHP tutorial and this is an example of Passed arguments.<br />
Argument-1: <?=$argument1?><br />
Argument-2: <?=$argument2?><br />

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/tests/Virat/Kunal

Upon execution, the above URL will produce the following output.

 

CakePHP Routing

How to Services in CakePHP

Services in CakePHP

Authentication

Components are the service layer in CakePHP, Authentication is the process of identifying the correct user. CakePHP supports three types of authentication.

  • FormAuthenticate − It allows you to authenticate users based on form POST data. Usually this is a login form that users enter information into. This is default authentication method.
  • BasicAuthenticate − It allows you to authenticate users using Basic HTTP authentication.
  • DigestAuthenticate − It allows you to authenticate users using Digest HTTP authentication.

Example for FormAuthentication

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('/auth',['controller'=>'Authexs','action'=>'index']);
      $routes->connect('/login',['controller'=>'Authexs','action'=>'login']);
      $routes->connect('/logout',['controller'=>'Authexs','action'=>'logout']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

Change the code of AppController.php file as shown in the following program.

src/Controller/AppController.php

<?php
   namespace App\Controller;
   use Cake\Controller\Controller;
   use Cake\Event\Event;
   use Cake\Controller\Component\AuthComponent;

   class AppController extends Controller{
      public function initialize(){
         parent::initialize();
         
         $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']
         ]);
      
         $this->Auth->config('authenticate', [
            AuthComponent::ALL => ['userModel' => 'users'], 'Form']);
      }
   
      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);
         }
      }
   }

Create AuthexsController.php file at src/Controller/AuthexsController.php. Copy the following code in the controller file.

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;

   class AuthexsController extends AppController{
      var $components = array('Auth');
      public function index(){
      }
      public function login(){
         if($this->request->is('post')){
            $user = $this->Auth->identify();
            
            if($user){
               $this->Auth->setUser($user);
               return $this->redirect($this->Auth->redirectUrl());
            } else
            $this->Flash->error('Your username or password is incorrect.');
         }
      }
      public function logout(){
         return $this->redirect($this->Auth->logout());
      }
   }
?>

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

You are successfully loggedout.

Create another View file called index.ctp. Copy the following code in that file.

src/Template/Authexs/index.ctp

You are successfully logged in. 
<?php echo 
   $this->Html->link('logout',["controller" => "Authexs","action" => "logout"]); 
?>

Execute the above example by visiting the following URL.

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.

Services Authexes

After providing the correct credentials, you will be logged in and redirected to the screen as shown below.

Services Auth

After clicking on the logout link, you will be redirected to the login screen again.

How to Session Management Tutorial in CakePHP

Session Management Tutorial in 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.

Accessing Session Object

Session object can be created by executing the following code.

$session = $this->request->session();

Writing Session Data

To write something in session, we can use the write() session method.

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’);

Reading Session Data

To retrieve stored data from session, we can use the read() session method.

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)

The above function will take only key as the argument.

Example

if ($session->check(‘name’)) { // name exists and is not null. }

Delete Session Data

To delete data from session, we can use the delete() session method to delete the data.

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)

The above function will take only key as argument.

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();

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 CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘/sessionobject’, [‘controller’=>’Sessions’,’action’=>’index’]); $routes->connect(‘/sessionread’, [‘controller’=>’Sessions’,’action’=>’retrieve_session_data’]); $routes->connect(‘/sessionwrite’, [‘controller’=>’Sessions’,’action’=>’write_session_data’]); $routes->connect(‘/sessioncheck’, [‘controller’=>’Sessions’,’action’=>’check_session_data’]); $routes->connect(‘/sessiondelete’, [‘controller’=>’Sessions’,’action’=>’delete_session_data’]); $routes->connect(‘/sessiondestroy’, [‘controller’=>’Sessions’,’action’=>’destroy_session_data’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a SessionsController.php file at src/Controller/SessionsController.php. Copy the following code in the controller file.

src/Controller/SessionsController.php

<?php namespace AppController; use AppControllerAppController; class SessionsController extends AppController{ public function retrieveSessionData(){ //create session object $session = $this->request->session(); //read data from session $name = $session->read(‘name’); $this->set(‘name’,$name); } public function writeSessionData(){ //create session object $session = $this->request->session(); //write data in session $session->write(‘name’,’Virat Gandhi’); } public function checkSessionData(){ //create session object $session = $this->request->session(); //check session data $name = $session->check(‘name’); $address = $session->check(‘address’); $this->set(‘name’,$name); $this->set(‘address’,$address); } public function deleteSessionData(){ //create session object $session = $this->request->session(); //delete session data $session->delete(‘name’); } public function destroySessionData(){ //create session object $session = $this->request->session(); //destroy session $session->destroy(); } } ?>

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

The data has been written in session.

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

Here is the data from session. Name: <?=$name;?>

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

<?php if($name): ?> name exists in the session. <?php else: ?> name doesn’t exist in the database <?php endif;?> <?php if($address): ?> address exists in the session. <?php else: ?> address doesn’t exist in the database <?php endif;?>

Create another filbe View 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

Data deleted from session.

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

Session

Visit the following URL to read session datahttp://localhost:85/CakePHP/session-read

CakePHP Sessions

Visit the following URL to check session datahttp://localhost:85/CakePHP/sessioncheck

Sessions

Visit the following URL to delete session datahttp://localhost:85/CakePHP/sessiondelete

Delete Session

Visit the following URL to destroy session datahttp://localhost:85/CakePHP/sessiondestroy

Session Destroyed

How to Set Email Configuration in CakePHP

how to set email configuration in cakephp

Email can be configured in file config/app.php. It is not required to define email configuration in config/app.php. Email can be used without it; just use the respective methods to set all configurations separately or load an array of configs. Configuration for Email defaults is created using config() and configTransport().

Email Configuration Transport

By defining transports separately from delivery profiles, you can easily re-use transport configuration across multiple profiles. You can specify multiple configurations for production, development and testing. Each transport needs a className. Valid options are as follows −

  • Mail − Send using PHP mail function
  • Smtp − Send using SMTP
  • Debug − Do not send the email, just return the result

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), ], ],

Email Delivery Profiles

Delivery profiles allow you to predefine various properties about email messages from your application and give the settings a name. This saves duplication across your application and makes maintenance and development easier. Each profile accepts a number of keys. Following is an example of Email delivery profiles.

Example

‘Email’ => [ ‘default’ => [ ‘transport’ => ‘default’, ‘from’ => ‘you@localhost’, ], ],