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

 

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

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