Google News
logo
CakePHP Interview Questions
CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. Our primary goal is to enable you to work in a structured and rapid manner–without loss of flexibility.
 
CakePHP takes the monotony out of web development. We provide you with all the tools you need to get started coding what you really need to get done: the logic specific to your application. Instead of reinventing the wheel every time you sit down to a new project, check out a copy of CakePHP and get started with the real guts of your application.
 
CakePHP has an active developer team and community, bringing great value to the project. In addition to keeping you from wheel-reinventing, using CakePHP means your application’s core is well tested and is being constantly improved.
 
Here’s a quick list of features you’ll enjoy when using CakePHP :
 
* Active, friendly community
* Flexible licensing
* Compatible with versions 4 and 5 of PHP
* Integrated CRUD for database interaction
* Application scaffolding
* Code generation
* MVC architecture
* Request dispatcher with clean, custom URLs and routes
* Built-in validation
* Fast and flexible templating (PHP syntax, with helpers)
* View Helpers for AJAX, JavaScript, HTML Forms and more
* Email, Cookie, Security, Session, and Request Handling Components
* Flexible ACL
* Data Sanitization
* Flexible Caching
* Localization
* Works from any web site directory, with little to no Apache configuration involved
In April 2005, CakePHP was developed by Michal Tatarynowicz. As a Polish programmer, he wrote a minimal version of a Rapid Application Framework in PHP, dubbing it Cake. CakePHP version 1.0 was released in May 2006.
System requirements for CakePHP are :
 
* PHP 5.4.16 or greater
* mbstring extension library
* intl extension
* MySQL with a minimum version of 5.5.3
* MariaDB with a minimum version of 5.5
* PostgreSQL
* SQLite 3
* Microsoft SQL server with a minimum of 2008 version
Here are the following server requirements for the installation of CakePHP:
 
* An HTTP Server such as Apache or Microsoft IIS.
* PHP with a minimum version of 5.6.
* intl, mbstring, simplexml, PDO PHO extension is required.
CakePHP follows the MVC software design pattern. Programming using MVC separates your application into three main parts :
 
1. The Model represents the application data
2. The View renders a presentation of model data
3. The Controller handles and routes requests made by the client
CakePHP MVC
Above Figure an example of a bare-bones MVC request in CakePHP. To illustrate, assume a client named “Ricardo” just clicked on the “Buy A Custom Cake Now!” link on your application’s home page.
 
* Ricardo clicks the link pointing to http://www.example.com/cakes/buy, and his browser makes a request to your web server.
 
* The dispatcher checks the request URL (/cakes/buy), and hands the request to the correct controller.
 
* The controller performs application specific logic. For example, it may check to see if Ricardo has logged in.
 
* The controller also uses models to gain access to the application’s data. Models usually represent database tables, but they could also represent LDAP entries, RSS feeds, or files on the system. In this example, the controller uses a model to fetch Ricardo’s last purchases from the database.
 
* Once the controller has worked its magic on the data, it hands it to a view. The view takes this data and gets it ready for presentation to the client. Views in CakePHP are usually in HTML format, but a view could just as easily be a PDF, XML document, or JSON object depending on your needs.
 
* Once the view has used the data from the controller to build a fully rendered view, the content of that view is returned to Ricardo’s browser.
 
Almost every request to your application will follow this basic pattern. We’ll add some details later on which are specific to CakePHP, so keep this in mind as we proceed.

Source : CakePHP
The CakePHP framework provides a robust base for your application. It can handle every aspect, from the user’s initial request all the way to the final rendering of a web page. And since the framework follows the principles of MVC, it allows you to easily customize and extend most aspects of your application.
 
The framework also provides a basic organizational structure, from filenames to database table names, keeping your entire application consistent and logical. This concept is simple but powerful. Follow the conventions and you’ll always know exactly where things are and how they’re organized.
 
* CakePHP Structure
* A Typical CakePHP Request
* CakePHP Folder Structure
* CakePHP Conventions
CakePHP works on MVC structure. MVC stands for the model view controller. MVC is an architectural pattern that describes a way to structure our application and explains the responsibilities and interactions of each part in that structure:
 
Model layer : This layer has business logic implemented for the application, such as retrieving data, converting or processing data, validating data that comes under this layer.

View layer : This layer is responsible for rendering the front-end interface from the information provided from the model data.

Controller layer : This layer is used to handle the request from the user. It gets requests from clients, checks its validity, fetches data accordingly, allocated resources, selects presentational data accordingly, and finally delegates the rendering process.
Hooks in CakePHP are callback functions that can be called before or after a database-related operation like accessing, modifying, deleting, or saving the data in the database. This method is used to do logic just before or after database operation.
 
Some other hooks are afterFind(), beforeValidate(), afterValidate(), beforeSave(), afterSave(), beforeDelete(), afterDelete(), and onError().
There are two ways to find the CakePHP version :
echo Configure::version()  
Or, go to the following path to find the version in the VERSION.txt file
/path/to/cake/lib/Cake/VERSION.txt
Different types of CakePHP supports are :
 
* File-Based
* APCu
* Redis
* Wincache
* XCache
* Memcached
It is a technique that allows a user to define and create a basic application that can create, update, retrieve and delete objects in cake PHP.
CakePHP is quite simple and easy to install :
 
* Mbstring PHP extension
* SimpleXML PHP extension
* Intl PHP extension
* HTTP server should have mod _rewrite is preferred
* PHP 5.6.0 or greater including PHP 7.2
Caching can be used to make reading from expensive or slow resources faster, by maintaining a second copy of the required data in a faster or closer storage system.
 
There are 5 built-in caching engines supported by CakePHP :
 
FileEngine : Uses simple files to store content. Poor performance, but good for storing large objects, or things that are not IO sensitive.

ApcEngine : Uses the APC object cache, one of the fastest caching engines.

MemcacheEngine : Uses the PECL::Memcache extension and Memcached for storage. Fast reads/writes, and benefits from memcache being distributed.

XcacheEngine : Uses the Xcache extension, an alternative to APC.

WincacheEngine : Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
CakePhp mainly supports four association types. They are
 
hasOne : One to One Relationship

hasMany : One to many Relationship

belongsTo : Many to One Relationship

hasAndBelongsToMany(HABTM) : Many to Many Relationship
Behaviors in CakePHP are a way to organize and enable horizontal re-use of Model layer logic. Conceptually they are similar to traits. However, behaviors are implemented as separate classes. This allows them to hook into the life-cycle callbacks that models emit, while providing trait-like features.
 
Behaviors provide a convenient way to package up behavior that is common across many models.
Scaffolding in CakePHP is an application creation technique used to create a basic application that does data operations such as create, read, update, & delete.
 
It is used to create a temporary quick application that is not in any way flexible. With scaffolding, you can also create or break the link between objects. To create scaffolding, you need to have a model and Controller defined. Then with a $scaffold variable in the Controller, you can create your application quickly.
In CakePHP, Cache makes your application run faster by storing complex query results for faster access. The types of cache supported by CakePHP are,
 
File cache : It is the simplest and slowest cache to store large elements.

APCu cache : It is a fast cache and uses shared memory to store elements. It provides basic read and writes features.

Wincache : It is the same APCu cache, but it is optimized for Windows.

Redis : It provides a fast and persistent cache.

Array : It is a run-time storage cache for storing elements in order.
To get the complete URL from the hostname, write the following command,
 
echo $this->Html->url(null, true);

Here, we set the full option to true. So, we get the full scheme, hostname, and project path. Suppose the above command gives the following result,
 
http://localhost/project/controller/action/1
PHP Sessions allows you to identify unique users across requests and store persistent data for specific users against a unique session ID. It is used to persist state information between page requests.
 
Session IDs are normally sent to the browser via session cookies, and the ID is used to retrieve existing session data.
 
You can access the session data any place you have access to a request object. It means the session is accessible from :
 
* Controllers
* Views
* Helpers
* Cells
* Components
CakePHP database layer provides help in working with a relational database like making a connection, building queries, making changes to the structure, preventing SQL injections, and many more. The following are some of the basic database functions that CakePHP offers,
 
Validating Data : With the validator object, you can check the type, shape, and size of the data before converting them into entities.

Saving Data : After loading and making changes to the data, you can use the save() function to insert or update the data into the database.

Deleting Data : With the delete() function, you can do different delete types like cascading delete, bulk delete, strict delete with the data.

Retrieving Data & Result set : With the help of the get() or find() function, you can retrieve the data. With the first() function, you can retrieve the resulting set.

Association : In CakePHP, different association types are available. With the help of this, you can like two or more databases.
In CakePHP, we can encrypt and decrypt data by using security library methods.
 
Syntax :
static Cake\Utility\Security::hash($string, $type = NULL, $salt = false)
We can create validator in controller by using given command :
use Cake\Validation\Validator;  

$validator = new Validator();
In CakePHP, there is several of logging level in CakePHP.
Logging level Description
Emergency System is unusable.
Alert Action must be taken immediately.
Critical Critical conditions
Error Error conditions
Warning Warning conditions
Notice Normal but significant condition
We can create an email delivery profile by using following command:
'Email' => [  

   'default' => [  

      'transport' => 'default',  

      'from' => 'you@localhost',  

   ],  

],
There are various types of events functions in Cake PHP :
Helper::beforeRender(Event $event, $viewFile)

Helper::beforeRenderFile(Event $event, $viewFile)

Helper::afterRender(Event $event, $viewFile)

Helper::afterLayout(Event $event, $layoutFile) etc.
CakePHP provides various security features to keep data or passwords safe.
 
* Security.salt is a hash that is used to encrypt or decrypt text messages in CakePHP.
Security::encrypt($text, $key, $hmacSalt = null) ​

Here, $hmacSalt() is the salt to use for HMAC process. Null is used to defined to use Security.salt
 
* Security.cipherSeed is nothing but the key used to encrypt or dedcrypt the message in Security::cipher() function.
Security::encrypt($text, $key, $hmacSalt = null)​

 

Here, $key is the 256 bit/32 byte cipher key or Security.cipherSeed
Helpers are associated with Presentation layers of application. It contains presentational logic, which is available to share between many views, elements, or layouts. Here are some commonly used helpers, such as :
 
* FormHelper
* HtmlHelper
* JsHelper
* CacheHelper
* NumberHelper
* Paginator
* RSS
* SessionHelper
* TextHelper
* TimeHelper
Two vendor folders are available in the CakePHP, one folder in the root and another is in the "app" folder.
 
The root one is the global vendor folder. It is used to place the third-party libraries which are used for multiple applications. The multiple apps share the same root (Cake + plugins + vendors)

The APP one is the app-specific one and takes precedence. It is used to place the third-party libraries which are application-specific.
The Application feature of CakePHP controls how the application is configured and what plugins, middleware, console commands, and routes are included.
 
Bootstrap : It is used to load configuration files, define constants, and other global functions.

Routes : It is used to load routes.

Middleware : It is used to add middleware to the application.

Console : It is used to add console commands to the application.

Events : It is used to add event listeners to the application event manager.
30 .
What is the use of $this->set() in CakePHP?
In CakePHP, this method is used to create variables in the view file.
$this->set('variable','value')   
Set in conjunction with the compact function is used to pass multiple variables to the view.
$this->set(compact('varible1','variable2','variable2',.......));   
And then that variable will be available to use in the view template file for that action.
* Session::read($key)function is used to read specific session data in CakePHP.
$this->Session->read('MysessionVar');  ​

*
Session::write($key, $value)function is used to write session data in CakePHP.
$this->Session->write('MysessionVar', "Hello");  ​


*
Session::delete($key)function is used to delete specific session data in CakePHP.

$this->Session->delete('MysessionVar');
Data validation is an important part of any application, as it helps to make sure that the data in a Model conforms to the business rules of the application. For example, you might want to make sure that passwords are at least eight characters long, or ensure that usernames are unique. Defining validation rules makes form handling much, much easier.
 
The first step to data validation is creating the validation rules in the Model. To do that, use the Model::validate array in the Model definition, for example:
<?php
class User extends AppModel {
    var $name = 'User';
    var $validate = array();
}
?>
In the example above, the $validate array is added to the User Model, but the array contains no validation rules. Assuming that the users table has login, password, email and born fields, the example below shows some simple validation rules that apply to those fields :
<?php
class User extends AppModel {
    var $name = 'User';
    var $validate = array(
        'login' => 'alphaNumeric',
        'email' => 'email',
        'born' => 'date'
    );
}
?>
The CakePHP Sanitize class can be used to rid user-submitted data of malicious data and other unwanted information. Sanitize is a core library, so it can be used anywhere inside of your code, but is probably best used in controllers or models.
 
CakePHP already protects you against SQL Injection if you use CakePHP’s ORM methods (such as find() and save()) and proper array notation (ie. array(‘field’ => $value)) instead of raw SQL. For sanitization against XSS its generally better to save raw HTML in database without modification and sanitize at the time of output/display.
 
All you need to do is include the Sanitize core library (e.g. before the controller class definition):
App::import('Sanitize');

class MyController extends AppController {
    ...
    ...
}
Once you’ve done that, you can make calls to Sanitize statically.
 
paranoid : paranoid(string $string, array $allowedChars);
 
This function strips anything out of the target $string that is not a plain-jane alphanumeric character. The function will overlook certain characters by passing them in $allowedChars array.
$badString = ";:<script><html><   // >@@#";
echo Sanitize::paranoid($badString);
// output: scripthtml
echo Sanitize::paranoid($badString, array(' ', '@'));
// output: scripthtml    @@
html : html(string $string, boolean $remove = false)
 
This method prepares user-submitted data for display inside HTML. This is especially useful if you don’t want users to be able to break your layouts or insert images or scripts inside of your HTML pages. If the $remove option is set to true, HTML content detected is removed rather than rendered as HTML entities.
$badString = '<font size="99" color="#FF0000">HEY</font><script>...</script>';
echo Sanitize::html($badString);
// output: &lt;font size=&quot;99&quot; color=&quot;#FF0000&quot;&gt;HEY&lt;/font&gt;&lt;script&gt;...&lt;/script&gt;
echo Sanitize::html($badString, true);
// output: HEY...
escape : escape(string $string, string $connection)
 
Used to escape SQL statements by adding slashes, depending on the system’s current magic_quotes_gpc setting. $connection is the name of the database to quote the string for, as named in your app/config/database.php file.

clean : Sanitize::clean(mixed $data, mixed $options)
 
This function is an industrial-strength, multi-purpose cleaner, meant to be used on entire arrays (like $this->data, for example). The function takes an array (or string) and returns the clean version. The following cleaning operations are performed on each element in the array (recursively) :
 
* Odd spaces (including 0xCA) are replaced with regular spaces.
* Double-checking special chars and removal of carriage returns for increased SQL security.
* Adding of slashes for SQL (just calls the sql function outlined above).
* Swapping of user-inputted backslashes with trusted backslashes.
CakePHP offers an easy and secure way to manage cookies. In CakePHP, CookieComponent class is used to manage cookies. It sets the cookie path, expiration, domain, key, encryption, and many more. To configure a cookie, you need to use the config() method.
$this->Cookie->config([   
   'expires' => '+5 days',   
   'httpOnly' => true   
]);  ​

 

The above function is used to create and configure the cookie. After configuring the cookie, you can read, write, delete, and check cookie data with various methods provided by the CookieComponent class.
A composer is a tool for managing project dependencies. You can create a CakePHP project using Composer by running the below commands on the terminal.
 
php composer.phar create-project --prefer-dist cakephp/app my_app_name

.ctp is the default extension of the view file. You can change default extension to write public $ext = '.yourextension' in AppController. If you want to change it for a particular controller, then add it to that particular Controller only.
 
You can also change it for the specific action of the Controller by putting it in that action only.
You can set Layout in the Controller by using the following command :
var $layout = 'layout_name';  
To overwrite for a specific action use below command :
$this->layout ="layout_name";
You can include Helpers in controller by using this command :
public $helpers = array('Form', 'Html', 'Js', 'Time');​
In specific action use below code :
$this->helper[] ="helper_name";  
You can include the components in controller by using the following command :
public $components = array('Emails', 'ImageUploader', 'Sms');
The following code is used to change the structure of the URL in an application.
url( string|array|null $url null , boolean $full false )
Callback function is used to so some logic before or after doing a database related operation. Some of the callback methods are,
 
beforeFind(array $query): This is called before doing find operation to execute the query that is passes to the function.

afterFind(array $results, boolean $primary = false): This is called after executing the find operation and is used to modify the results from it.

beforeValidate(array $options = array()) : It is used to modify data before it is validated.

afterValidate() : It is used to do data clean up after validation process.

beforeSave(array $options = array()) : It is used to do any logic before saving operation.

beforeSave(array $options = array()) : It is used to do logic after the save operation.

beforeDelete(boolean $cascade = true) : It is used to do pre-deletion logic.

afterDelete() : It is used to do logic after deletion.

onError() : It is called if any error occurs.
There are many types of associations in CakePHP that links are used to link different models. HABTM (Has And Belongs To Many) is a type of model association in CakePHP. HABTM is used to associate two models in many ways and repeatedly.
 
The unique thing about HABTM is that the link between the models is no exclusive. Also, the data in HABTM is a complete set. So, each time a new data association is added, the complete set in HABTM is dropped and created again.
In CakePHP working with data through the database is done with two primary object types. The first are repositories or table objects. These objects provide access to collections of data. They allow you to save new records, modify/delete existing ones, define relations, and perform bulk operations. The second type of objects are entities. Entities represent individual records and allow you to define row/record level behavior & functionality.
 
These two classes are usually responsible for managing almost everything that happens regarding your data, its validity, interactions and evolution of the information workflow in your domain of work.
 
CakePHP’s built-in ORM specializes in relational databases, but can be extended to support alternative datasources.
 
The CakePHP ORM borrows ideas and concepts from both ActiveRecord and Datamapper patterns. It aims to create a hybrid implementation that combines aspects of both patterns to create a fast, simple to use ORM.

Quick Example : To get started you don’t have to write any code. If you’ve followed the CakePHP conventions for your database tables you can just start using the ORM. For example if we wanted to load some data from our articles table we would start off creating our Articles table class. Create src/Model/Table/ArticlesTable.php with the following code:
<?php
namespace App\Model\Table;

use Cake\ORM\Table;

class ArticlesTable extends Table
{
}
Then in a controller or command we can have CakePHP create an instance for us:
public function someMethod()
{
    $resultset = $this->fetchTable('Articles')->find()->all();

    foreach ($resultset as $row) {
        echo $row->title;
    }
}
In other contexts, you can use the LocatorAwareTrait which add accessor methods for ORM tables:
use Cake\ORM\Locator\LocatorAwareTrait;

public function someMethod()
{
    $articles = $this->getTableLocator()->get('Articles');
    // more code.
}
Within a static method you can use the Datasource\FactoryLocator to get the table locator:
 
$articles = TableRegistry::getTableLocator()->get('Articles');

Table classes represent collections of entities. Next, lets create an entity class for our Articles. Entity classes let you define accessor and mutator methods, define custom logic for individual records and much more. We’ll start off by adding the following to src/Model/Entity/Article.php after the <?php opening tag :
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Article extends Entity
{
}
Entities use the singular CamelCase version of the table name as their class name by default. Now that we have created our entity class, when we load entities from the database we’ll get instances of our new Article class:
use Cake\ORM\Locator\LocatorAwareTrait ;

$articles = $this->getTableLocator()->get('Articles');
$resultset = $articles->find()->all();

foreach ($resultset as $row) {
    // Each row is now an instance of our Article class.
    echo $row->title;
}
CakePHP uses naming conventions to link the Table and Entity class together. If you need to customize which entity a table uses you can use the entityClass() method to set a specific classname.
 
See the chapters on Table Objects and Entities for more information on how to use table objects and entities in your application.
class Cake\Utility\Inflector

The Inflector class takes a string and can manipulate it to handle word variations such as pluralization or camelizing and is normally accessed statically. Example:
Inflector::pluralize('example') returns “examples”.
 
You can try out the inflections online at inflector.cakephp.org or sandbox.dereuromark.de.
 
Summary of Inflector Methods and Their Output : Quick summary of the Inflector built-in methods and the results they output when provided a multi-word argument :
Method Argument Output

pluralize()

BigApple

BigApples

big_apple

big_apples

singularize()

BigApples

BigApple

big_apples

big_apple

camelize()

big_apples

BigApples

big apple

BigApple

underscore()

BigApples

big_apples

Big Apples

big apples

humanize()

big_apples

Big Apples

bigApple

BigApple

classify()

big_apples

BigApple

big apple

BigApple

dasherize()

BigApples

big-apples

big apple

big apple

tableize()

BigApple

big_apples

Big Apple

big apples

variable()

big_apple

bigApple

big apples

bigApples

The registry classes provide a simple way to create and retrieve loaded instances of a given object type. There are registry classes for Components, Helpers, Tasks, and Behaviors.
 
While the examples below will use Components, the same behavior can be expected for Helpers, Behaviors, and Tasks in addition to Components.
 
Loading Objects : Objects can be loaded on-the-fly using add<registry-object>() Example :
$this->loadComponent('Acl.Acl');
$this->addHelper('Flash')
This will result in the Acl property and Flash helper being loaded. Configuration can also be set on-the-fly. Example:
$this->loadComponent('Cookie', ['name' => 'sweet']);
Any keys and values provided will be passed to the Component’s constructor. The one exception to this rule is className. Classname is a special key that is used to alias objects in a registry. This allows you to have component names that do not reflect the classnames, which can be helpful when extending core components:
$this->Auth = $this->loadComponent('Auth', ['className' => 'MyCustomAuth']);
$this->Auth->user(); // Actually using MyCustomAuth::user();
Triggering Callbacks : Callbacks are not provided by registry objects. You should use the events system to dispatch any events/callbacks for your application.
 
Disabling Callbacks : In previous versions, collection objects provided a disable() method to disable objects from receiving callbacks. You should use the features in the events system to accomplish this now. For example, you could disable component callbacks in the following way:
// Remove Auth from callbacks.
$this->getEventManager()->off($this->Auth);

// Re-enable Auth for callbacks.
$this->getEventManager()->on($this->Auth);