How to View Events, Callbacks in CakePHP

View Events, Callbacks in 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.

S.No Event Function & Description
1 Helper::beforeRender(Event $event, $viewFile)

The beforeRender method is called after the controller’s beforeRender method but before the controller renders view and layout. This receives the file being rendered as an argument.

2 Helper::beforeRenderFile(Event $event, $viewFile)

This method is called before each view file is rendered. This includes elements, views, parent views and layouts.

3 Helper::afterRenderFile(Event $event, $viewFile, $content)

This method is called after each View file is rendered. This includes elements, views,parent views and layouts. A callback can modify and return $content to change how the rendered content will be displayed in the browser.

4 Helper::afterRender(Event $event, $viewFile)

This method is called after the view has been rendered but before the layout rendering has started.

5 Helper::beforeLayout(Event $event, $layoutFile)

This method is called before the layout rendering starts. This receives the layout filename as an argument.

6 Helper::afterLayout(Event $event, $layoutFile)

This method is called after the layout rendering is complete. This receives the layout filename as an argument.

How to View Elements in CakePHP

View Elements in 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.

Cake\View\View::element(string $elementPath, array $data, array $options =[])

There are three arguments to the above function −

  • The first argument is the name of the template file in the /src/Template/Element/ folder.
  • The second argument is the array of data to be made available to the rendered view.
  • The third argument is for the array of options. e.g. cache.

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

Element Example: <?php echo $this→element('helloworld'); ?>

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('/elementexample',['controller'=>'Elems','action'=>'index']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

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

src/Controller/ElemsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController; 
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;

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

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/element-example

Output

Upon execution, the above URL will give you the following output.

How to view records from Database in CakePHP

view records in CakePHP

To view records in CakePHP and To monitor records of database, we 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) {
      $routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);
      $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 App\Controller;
   use App\Controller\AppController;
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;

   class UsersController extends AppController{
      public function index(){
         $users = TableRegistry::get('users');
         $query = $users->find();
         $this->set('results',$query);
      }
   }
?>

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

<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>

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/users

Output

Upon execution, the above URL will give you the following output.

View a Record in CakePHP

click here to read more cakePHP official website

 

Read more:

How to fix Potential for Information Disclosure in CakePHP

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.

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 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 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