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.
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.
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.
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 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.
CakePHP is an open source Rapid Development MVC framework written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License. It makes developing, deploying and maintaining applications much easier. CakePHP has number of libraries to reduce the overload of most common tasks. Following are the advantages of using CakePHP.
Email, Cookie, Security, Session, and Request Handling Components
View Helpers for AJAX, JavaScript, HTML Forms and More
CakePHP Request Cycle
The following illustration describes how a Request Lifecycle works −
A typical CakePHP request cycle starts with a user requesting a page or resource in your application. At a high level, each request goes through the following steps −
The webserver rewrite rules direct the request to webroot/index.php.
Your application’s autoloader and bootstrap files are executed.
Any dispatch filters that are configured can handle the request, and optionally generate a response.
The dispatcher selects the appropriate controller & action based on routing rules.
The controller’s action is called and the controller interacts with the required Models and Components.
The controller delegates response creation to the View to generate the output resulting from the model data.
The view uses Helpers and Cells to generate the response body and headers.
The response is sent back to the client.
Initial release: April 2005; 13 years ago
Stable release: 3.6.2 / 2018-04-27
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.
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.
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.
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.
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.
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.
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 −
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:
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.