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