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

 

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

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 Generating URLs in CakePHP

Generating URLs in CakePHP

This is a cool feature of CakePHP. Using the generated URLs, we can easily change the structure of URL in the application without modifying the whole code.

url( string|array|null $url null , boolean $full false )

The above function will take two arguments −

  • The first argument is an array specifying any of the following − ‘controller’, ‘action’, ‘plugin’. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string.
  • If true, the full base URL will be prepended to the result. Default is false.

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', function (RouteBuilder $routes){ $routes->connect('/generate',
['controller'=>'Generates','action'=>'index']); }); 
Plugin::routes();

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

src/Controller/GeneratesController.php

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

Create a folder Generates at src/Template and under that folder create a View file called index.ctp. Copy the following code in that file.

src/Template/Generates/index.ctp

This is CakePHP tutorial and this is an example of Generating URLs.

Execute the above example by visiting the following URL −

http://localhost:85/CakePHP/generate

Tutorials on Form Handling, Building HTML in CakePHP

Tutorials on Form Handling, Building HTML in CakePHP

Form is a simple input taker in applications, defined inputs by users need authentication and formatting to be stored. Cakephp makes easy FormHelper to work with form. It is quick and will streamline validation, re-population and layout.

CakePHP – Form Handling

CakePHP provides various in built tags to handle HTML forms easily and securely. Like many other PHP frameworks, major elements of HTML are also generated using CakePHP. Following are the various functions used to generate HTML elements.

The following functions are used to generate select options.

Syntax _selectOptions( array $elements array(), array $parents array(), boolean $showParents null, array $attributes array() )
Parameters
  • Elements to format
  • Parents for OPTGROUP
  • Whether to show parents
  • HTML attributes
Returns array
Description Returns an array of formatted OPTION/OPTGROUP elements

The following functions are used to generate HTML select element.

Syntax select( string $fieldName, array $options array(), array $attributes array() )
Parameters Name attribute of the SELECT

Array of the OPTION elements (as ‘value’=>’Text’ pairs) to be used in the SELECT element

The HTML attributes of the select element.

Returns Formatted SELECT element
Description Returns a formatted SELECT element

The following functions are used to generate button on HTML page.

Syntax Button (string $title, array $options array() )
Parameters
  • The button’s caption. Not automatically HTML encoded.
  • Array of options and HTML attributes.
Returns HTML button tag.
Description Creates a <button> tag. The type attribute defaults to type=”submit“. You can change it to a different value by using $options[‘type’].

The following functions are used to generate checkbox on HTML page.

Syntax Checkbox (string $fieldName, array $options array() )
Parameters
  • Name of a field, like this “Modelname.fieldname”
  • Array of HTML attributes. Possible options are value, checked, hiddenField, disabled, default.
Returns An HTML text input element.
Description Creates a checkbox input widget.

The following functions are used to create form on HTML page.

Syntax create( mixed $model null, array $options array() )
Parameters
  • The model name for which the form is being defined. Should include the plugin name for plugin models. e.g. ContactManager.Contact. If an array is passed and $options argument is empty, the array will be used as options. If false no model is used.
  • An array of html attributes and options. Possible options are type, action, url, default, onsubmit, inputDefaults, encoding
Returns A formatted opening FORM tag.
Description Returns an HTML FORM element.

The following functions are used to provide file uploading functionality on HTML page.

Syntax file(string $fieldName, array $options array() )
Parameters
  • Name of a field, in the form “Modelname.fieldname”
  • Array of HTML attributes.
Returns A generated file input.
Description Creates file input widget.

The following functions are used to create hidden element on HTML page.

Syntax hidden( string $fieldName, array $options array() )
Parameters
  • Name of a field, in the form of “Modelname.fieldname”
  • Array of HTML attributes.
Returns A generated hidden input
Description Creates a hidden input field

The following functions are used to generate input element on HTML page.

Syntax Input (string $fieldName, array $options array() )
Parameters
  • This should be “Modelname.fieldname”
  • Each type of input takes different options
Returns Completed form widget
Description Generates a form input element complete with label and wrapper div

The following functions are used to generate radio button on HTML page.

Syntax Radio (string $fieldName, array $options array(), array $attributesarray() )
Parameters
  • Name of a field, like this “Modelname.fieldname”
  • Radio button options array.
  • Array of HTML attributes, and special attributes above.
Returns Completed radio widget set
Description Creates a set of radio widgets. Will create a legend and fieldset by default. Use $options to control this.

The following functions are used to generate submit button on HTML page.

Syntax Submit (string $caption null, array $options array() )
Parameters
  • The label appearing on the button OR if string contains :// or the extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension exists, AND the first character is /, image is relative to webroot, OR if the first character is not /, image is relative to webroot/img.
  • Array of options. Possible options are div, before, after, type etc.
Returns An HTML submit button
Description Creates a submit button element. This method will generate <input/> elements that can be used to submit, and reset forms by using $options. Image submits can be created by supplying an image path for $caption.

The following functions are used to generate textarea element on HTML page.

Syntax Textarea (string $fieldName, array $options array() )
Parameters
  • Name of a field, in the form “Modelname.fieldname”
  • Array of HTML attributes, special option like escape
Returns A generated HTML text input element
Description Creates a textarea widget

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(‘register’,[‘controller’=>’Registrations’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

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

src/Controller/RegistrationController.php

<?php namespace AppController; use AppControllerAppController; class RegistrationsController extends AppController{ public function index(){ $country = array(‘India’,’United State of America’,’United Kingdom’); $this->set(‘country’,$country); $gender = array(‘Male’,’Female’); $this->set(‘gender’,$gender); } } ?>

Create a directory Registrations at src/Template and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Registrations/index.ctp

<?php echo $this->Form->create(“Registrations”,array(‘url’=>’/register’)); echo $this->Form->input(‘username’); echo $this->Form->input(‘password’); echo $this->Form->input(‘password’); echo ‘<label for=”country”>Country</label>’; echo $this->Form->select(‘country’,$country); echo ‘<label for=”gender”>Gender</label>’; echo $this->Form->radio(‘gender’,$gender); echo ‘<label for=”address”>Address</label>’; echo $this->Form->textarea(‘address’); echo $this->Form->file(‘profilepic’); echo ‘

‘.$this->Form->checkbox(‘terms’). ‘

‘; echo $this->Form->button(‘Submit’); echo $this->Form->end(); ?>

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

Output

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