Application Configuration Tutorials on CakePHP

Application Configuration Tutorials on CakePHP

Configuring your Application

Configuration is generally stored in either PHP or INI files, and loaded during the application bootstrap. CakePHP comes with one configuration file by default, but if required you can add additional configuration files and load them in your application’s bootstrap code. Cake\Core\Configure is used for global configuration, and classes like Cache provide config() methods to make configuration simple and transparent.

Loading Additional Configuration Files

If your application has many configuration options it can be helpful to split configuration into multiple files. After creating each of the files in your config/ directory you can load them in bootstrap.php:

use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;

Configure::config('default', new PhpConfig());
Configure::load('app', 'default', false);
Configure::load('other_config', 'default');

You can also use additional configuration files to provide environment specific overrides. Each file loaded after app.php can redefine previously declared values allowing you to customize configuration for development or staging environments.

General Configuration

The following table describes the role of various variables and how they affect your CakePHP application.

S.No Variable Name & Description
1 debug

Changes CakePHP debugging output.

false = Production mode. No error messages, errors, or warnings shown.

true = Errors and warnings shown.

2 App.namespace

The namespace to find app classes under.

3 App.baseUrl

Un-comment this definition if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too.

4 App.base

The base directory the app resides in. If false, this will be auto detected.

5 App.encoding

Define what encoding your application uses. This encoding is used to generate the charset in the layout, and encode entities. It should match the encoding values specified for your database.

6 App.webroot

The webroot directory.

7 App.wwwRoot

The file path to webroot.

8 App.fullBaseUrl

The fully qualified domain name (including protocol) to your application’s root.

9 App.imageBaseUrl

Web path to the public images directory under webroot.

10 App.cssBaseUrl

Web path to the public css directory under webroot.

11 App.jsBaseUrl

Web path to the public js directory under webroot.

12 App.paths

Configure paths for non-class based resources. Supports the plugins, templates, locales subkeys, which allow the definition of paths for plugins, view templates and locale files respectively.

13 Security.salt

A random string used in hashing. This value is also used as the HMAC salt when doing symmetric encryption.

14 Asset.timestamp

Appends a timestamp which is last modified time of the particular file at the end of asset files URLs (CSS, JavaScript, Image) when using proper helpers. Valid values −

  • (bool) false – Doesn’t do anything (default)
  • (bool) true – Appends the timestamp when debug is true
  • (string) ‘force’ – Always appends the timestamp

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.

Let’s understand each parameter in detail −

S.NO Key & Description
1 className

The fully namespaced class name of the class that represents the connection to a database server. This class is responsible for loading the database driver, providing SQL transaction mechanisms and preparing SQL statements among other things.

2 driver

The class name of the driver used to implements all specificities for a database engine. This can either be a short classname using plugin syntax, a fully namespaced name, or a constructed driver instance. Examples of short classnames are Mysql, Sqlite, Postgres, and Sqlserver.

3 persistent

Whether or not to use a persistent connection to the database.

4 host

The database server’s hostname (or IP address).

5 username

Database username

6 password

Database password

7 database

Name of Database

8 port (optional)

The TCP port or Unix socket used to connect to the server.

9 encoding

Indicates the character set to use when sending SQL statements to the server like ‘utf8’ etc.

10 timezone

Server timezone to set.

11 schema

Used in PostgreSQL database setups to specify which schema to use.

12 unix_socket

Used by drivers that support it to connect via Unix socket files. If you are using PostgreSQL and want to use Unix sockets, leave the host key blank.

13 ssl_key

The file path to the SSL key file. (Only supported by MySQL).

14 ssl_cert

The file path to the SSL certificate file. (Only supported by MySQL).

15 ssl_ca

The file path to the SSL certificate authority. (Only supported by MySQL).

16 init

A list of queries that should be sent to the database server as when the connection is created.

17 log

Set to true to enable query logging. When enabled queries will be logged at a debug level with the queriesLog scope.

18 quoteIdentifiers

Set to true if you are using reserved words or special characters in your table or column names. Enabling this setting will result in queries built using the Query Builder having identifiers quoted when creating SQL. It decreases performance.

19 flags

An associative array of PDO constants that should be passed to the underlying PDO instance.

20 cacheMetadata

Either boolean true, or a string containing the cache configuration to store meta data in. Having metadata caching disable is not advised and can result in very poor performance.

 

Tutorials on CakePHP Controllers in Details

Tutorials on CakePHP Controllers

Controllers are the ‘C’ in MVC. After routing has been applied and the correct controller has been found, your controller’s action is called. Your controller should handle interpreting the request data, making sure the correct models are called, and the right response or view is rendered. Controllers can be thought of as middle layer between the Model and View. You want to keep your controllers thin, and your models fat. This will help you reuse your code and makes your code easier to test.

Commonly, a controller is used to manage the logic around a single model. For example, if you were building a site for an online bakery, you might have a RecipesController managing your recipes and an IngredientsController managing your ingredients. However, it’s also possible to have controllers work with more than one model. In CakePHP, a controller is named after the primary model it handles.

Your application’s controllers extend the AppController class, which in turn extends the core Controller class. The AppController class can be defined in src/Controller/AppController.php and it should contain methods that are shared between all of your application’s controllers.

Controllers provide a number of methods that handle requests. These are called actions. By default, each public method in a controller is an action, and is accessible from a URL. An action is responsible for interpreting the request and creating the response. Usually responses are in the form of a rendered view, but there are other ways to create responses as well.

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.

namespace App\Controller;

use Cake\Controller\Controller;

class AppController extends Controller
{
}

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

class RecipesController extends AppController{ public function view($id){ // Action logic goes here. } public function share($customerId, $recipeId){ // Action logic goes here. } public function search($query){ // Action logic goes here. } }

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 −

Syntax

CakeControllerController::setAction($action, $args…)

The following code will redirect the user to index action of the same controller.

$this->setAction(‘index’);

The following example shows the usage of the above method.

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(‘/redirectcontroller’,[‘ controller’=>’Redirects’,’action’=>’action1′]); $routes->connect(‘/redirectcontroller2’,[‘ controller’=>’Redirects’,’action’=>’action2′]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

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

src/Controller/RedirectsController.php

<?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; class RedirectsController extends AppController{ public function action1(){ } public function action2(){ echo “redirecting from action2”; $this->setAction(‘action1’); } } ?>

Create a directory Redirects at src/Template and under that directory create a Viewfile called action1.ctp. Copy the following code in that file.

src/Template/Redirects/action1.ctp

This is an example of how to redirect within controller.

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/redirect-controller

Output

Upon execution, you will receive the following output.

Redirects

Now, visit the following URL − http://localhost:85/CakePHP/redirect-controller2

The above URL will give you the following output.

Redirecting Action2

Loading Models

In CakePHP, a model can be loaded using the loadModel() method. The following is the syntax for the loadModel() method.

Syntax

CakeControllerController::loadModel(string $modelClass, string $type)

There are two arguments to the above function −

  • The first argument is the name of model class.
  • The second argument is the type of repository to load.

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

Read more from CakePHP Official Documentation – Controllers 3.7

How to Manage Cookie in CakePHP

How to Manage Cookie in 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.

CakeControllerComponentCookieComponent::write(mixed $key, mixed $value = null)

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’, ‘John’);

We can pass array of name, values pair to write multiple cookies.

Read Cookie

The read() method is used to read cookie. Following is the syntax of the read() method.

CakeControllerComponentCookieComponent::read(mixed $key = null)

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.

CakeControllerComponentCookieComponent::check($key)

Example

echo $this->Cookie->check(‘name’);

Delete Cookie

The delete() method is used to delete cookie. Following is the syntax of the delete() method.

CakeControllerComponentCookieComponent::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 CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; 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’); }); Plugin::routes();

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

src/Controller/Cookies/CookiesController.php

<?php namespace AppController; use AppControllerAppController; use CakeControllerComponentCookieComponent; class CookiesController extends AppController{ public $components = array(‘Cookie’); public function writeCookie(){ $this->Cookie->write(‘name’, ‘John’); } public function readCookie(){ $cookie_val = $this->Cookie->read(‘name’); $this->set(‘cookie_val’,$cookie_val); } public function checkCookie(){ $isPresent = $this->Cookie->check(‘name’); $this->set(‘isPresent’,$isPresent); } public function deleteCookie(){ $this->Cookie->delete(‘name’); } } ?>

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.

src/Template/Cookie/write_cookie.ctp

The cookie has been written.

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

The value of the cookie is: <?php echo $cookie_val; ?>

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

The cookie has been deleted.

Output

Execute the above example by visiting the following URL − http://localhost:85/CakePHP/cookie/write

This will help you write data in cookie.

Cookies

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

CakePHP Cookies

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

CakePHP Cookies

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

Cookies Deleted

 

How to Create Validators in CakePHP

Create Validators in CakePHP

Validator can be created by adding the following two lines in the controller.

use CakeValidationValidator; $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.

$validator->notEmpty(‘username’, ‘We need username.’)->add(‘username’, ‘validFormat’, [‘rule’ => ’email’,’message’ => ‘E-mail must be valid’]); $validator->notEmpty(‘password’, ‘We need password.’); $errors = $validator->errors($this->request->data());

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 CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘validation’,[‘controller’=>’Valids’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

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

src/Controller/ValidsController.php

<?php namespace AppController; use AppControllerAppController; use CakeValidationValidator; class ValidsController extends AppController{ public function index(){ $validator = new Validator(); $validator->notEmpty(‘username’, ‘We need username.’) ->add(‘username’, ‘validFormat’, [‘rule’ => ’email’,’message’ => ‘E-mail must be valid’]); $validator->notEmpty(‘password’, ‘We need password.’); $errors = $validator->errors($this->request->data()); $this->set(‘errors’,$errors); } } ?>

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&gtl’; } 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(); ?>

Execute the above example by visiting the following URL −http://localhost:85/CakePHP/validation

Output

Click on the submit button without entering anything.

How to Delete Records from Database Table in CakePHP

Delete Records from Database Table in 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 CakeCorePlugin;
use CakeRoutingRouteBuilder;
use CakeRoutingRouter;
Router::defaultRouteClass(‘DashedRoute’);
Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘/users/delete’,
[‘controller’ => ‘Users’, ‘action’ => ‘delete’]); $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 delete($id){ $users_table = TableRegistry::get(‘users’); $users = $users_table->get($id); $users_table->delete($users);
echo “User deleted successfully.”; $this->setAction(‘index’); } } ?>

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

Add User

 

ID Username Password Edit Delete

Execute the above example by visiting the following URL and click on Delete link to delete record.

http://localhost:85/CakePHP/users

How to Handle Errors and Exception in CakePHP

How to Handle Errors and Exception in 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.

Errors and Exception Configuration

Errors and Exception can be configured in file configapp.php. Error handling accepts a few options that allow you to tailor error handling for your application −

Option Data Type Description
errorLevel int The level of errors you are interested in capturing. Use the built-in php error constants, and bitmasks to select the level of error you are interested in.
trace bool Include stack traces for errors in log files. Stack traces will be included in the log after each error. This is helpful for finding where/when errors are being raised.
exceptionRenderer string The class responsible for rendering uncaught exceptions. If you choose a custom class, you should place the file for that class in src/Error. This class needs to implement a render() method.
log bool When true, exceptions + their stack traces will be logged to CakeLogLog.
skipLog array An array of exception classnames that should not be logged. This is useful to remove NotFoundExceptions or other common, but uninteresting logs messages.
extraFatalErrorMemory int Set to the number of megabytes to increase the memory limit by when a fatal error is encountered. This allows breathing room to complete logging or error handling.

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('/exception/:arg1/:arg2',[ 'controller'=>'Exps','action'=>'index'],['pass' => ['arg1', 'arg2']]); $routes->fallbacks('DashedRoute'); }); 
Plugin::routes();

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

src/Controller/ExpsController.php

<?php namespace AppController; 
use AppControllerAppController; 
use CakeCoreExceptionException; 
class ExpsController extends AppController{ public function index($arg1,$arg2){ try{ $this->set('argument1',$arg1); $this->set('argument2',$arg2); 
if(($arg1 < 1 || $arg1 > 10) || ($arg2 < 1 || $arg2 > 10)) throw new Exception("One of the number is out of range[1-10]."); }
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

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

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/exception/5/0

How to Extend Views in CakePHP

Extend Views in 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 CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', function (RouteBuilder $routes) { $routes->connect('extend',['controller'=>'Extends','action'=>'index']); $routes->fallbacks('DashedRoute'); }); 
Plugin::routes();

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

src/Controller/ExtendsController.php

<?php namespace AppController; use AppControllerAppController; class ExtendsController extends AppController{ public function index(){ } } ?>

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

Common Header

<?= $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

<?php $this->extend('header'); ?>

This is an example of extending view.

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/extend

Output

Upon execution, you will receive the following output.