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 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 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 Update a Record in CakePHP

Update a Record in 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 CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘/users/edit’, [‘controller’ => ‘Users’, ‘action’ => ‘edit’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

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

src/controller/UsersController.php

<?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; class UsersController extends AppController{ public function index(){ $users = TableRegistry::get(‘users’); $query = $users->find(); $this->set(‘results’,$query); } public function edit($id){ 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); } } } ?>

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

<a href = “add”>Add User</a> <table> <tr> <td>ID</td> <td>Username</td> <td>Password</td> <td>Edit</td> <td>Delete</td> </tr> <?php foreach ($results as $row): 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>

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

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.

Update a Record

How to Useful Resources in CakePHP

Useful Resources in CakePHP

The software comes with features such as code generation and scaffolding, which allow developers to build prototypes of websites quickly without having to worry about complicated XML or YAML files. Cake PHP has become a useful technology for almost everyone regardless if they are developers or no. If you want to get on the delicious CakePHP training, it is not yet too late. Here are a few resources that you can use to start learning CakePHP.

The following resources contain additional information on CakePHP. Please use them to get more in-depth knowledge on this.

Useful Links on CakePHP

Useful Books on CakePHP

  • CakePHP 2 Application Cookbook
  • Beginning CakePHP
  • CakePHP Application Development
  • Learn Cakephp
  • Instant CakePHP Starter
  • Practical CakePHP Projects

 

How to Validation Package in CakePHP

Validation Package in 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.

Syntax Add (string $field, array|string $name, array|CakeValidationValidationRule $rule [] )
Parameters
  • The name of the field from which the rule will be added.
  • The alias for a single rule or multiple rules array.
  • The rule to add
Returns $this
Description Adds a new rule to a field’s rule set. If second argument is an array, then rules list for the field will be replaced with second argument and third argument will be ignored.
Syntax allowEmpty (string $field, boolean|string|callable $when true, string|null $message null)
Parameters
  • The name of the field.
  • Indicates when the field is allowed to be empty. Valid values are true (always), ‘create’, ‘update’. If a callable is passed, then the field will be left empty only when the callback returns true.
  • The message to show if the field is not.
Returns $this
Description Allows a field to be empty.
Syntax alphanumeric (string $field, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add an alphanumeric rule to a field.
Syntax creditCard (string $field, string $type ‘all’, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • 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’].
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a credit card rule to a field.
Syntax Email (string $field, boolean $checkMX false, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • Whether or not to check the MX records.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add an email validation rule to a field.
Syntax maxLength (string $field, integer $max, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The maximum length allowed.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a string length validation rule to a field.
Syntax minLength (string $field, integer $min, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The maximum length allowed.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a string length validation rule to a field.
Syntax notBlank (string $field, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a notBlank rule to a field.

Folder Structure Overview in CakePHP

Folder Structure Overview in CakePHP

CakePHP – Folder Structure

The following table describes the role of each folder −

S.No Folder Name & Description
1 bin

The bin folder holds the Cake console executables.

2 config

The config folder holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.

3 logs

The logs folder normally contains your log files, depending on your log configuration.

4 plugins

The plugins folder is where the Plugins your application uses are stored.

5 src

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.

  • Console Contains the console commands and console tasks for your application.
  • Controller Contains your application’s controllers and their components.
  • Locale Stores string files for internationalization.
  • Model Contains your application’s tables, entities and behaviors.
  • View Presentational classes are placed here: cells, helpers, and template files.
  • Template Presentational files are placed here: elements, error pages, layouts, and view template files.
6 tests

The tests folder will be where you put the test cases for your application.

7 tmp

The tmp folder 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 and sometimes session information.

8 vendor

The vendor folder is where CakePHP and other application dependencies will be installed. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core.

9 webroot

The webroot directory is the public document root of your application. It contains all the files you want to be publically reachable.