Category Archives: CakePHP

CakePHP interview questions and tutorials along with expert tips and tricks

In How many ways we can use Model in CakePHP

CakePHP is an MVC based framework and facilitates unlimited flexibility. A model in cake PHP is used for the data source and all the logics that require to gather the data.

Later we use a Model functions to get these formatted data in Controllers and send them to view using the set function.

Here we are going to learn in how many ways we can use a Model or data source in CakePHP applications.

The naming convention followed in CakePHP help us to reduce our effort and to make the development process rapid.

Since Model is used as a logical unit and data source we can use it in any Controller where we need the data, irrespective the name of model and controllers.

A Controller with name “Users” can access the functions written in Model User without any manual initialization. But the question is how to use another Model and its functions in Users Controller?

When we are developing a complex application we usually need to access data from many tables or we can say from many Models in a single controller.

If there is no association then we need to initialize the other Models manually. Once we initialize these models we can use any functions in these models in the Controller. We can use any data source in any controller.

Even we can use the Model in our plugins Model, in the same way, we use in our standard models.

There are different ways to initialize a model in any Controller:

  • Initialize at the start of Controller and use it in any action of Controller.
  • Initialize in the particular action of Controller.
  • Initialize and Using in Another model.

Initialize at the start of Controller and use it in any action of Controller

There are many such situations when we need to use any model continuously in all the functions, then we need to initialize a model that can be used from anywhere.

Here we once initialize the model is available anywhere in a controller to use. We should not use this method when we are using the Model in only a few functions.

This may create overhead to the application when each time a data source is being loaded without reason.

Initialize in a particular action of Controller

When we have limited usage in a controller then it is not a good practice to initialize a model at the start.

We should initialize when we need only.

There may be some particular function that needs to access data from another model.

Initialize and Using in Another model

There are many such situations arrived when you need to use another model functions in your model, then you need to import that model in your model.

When we need additional data apart from association we need to fetch data from a model that is not the current model. CakePHP provides flexibility to use a number of existing model functions in your model.

This facilitates code reusability and improves the maintainability of application and at the same time reduce overhead and development time.

Hope this article will help you in using a model in Cake PHP in different ways.

Happy Learning 🙂

Spread the love

CakePHP 4.0.0 alpha is released

The new and most awaited version of the rapid development framework is released by the core team of CakePHP.

The alpha released yet is not recommended for development purpose, until the stable version come. Removing the drawbacks and implementing new features , library support and improved performance the new version of cakephp will be rocking soon.

What are the new features in CakePHP 4.0.0

The Directory structure and the Bake console is rewritten to ease the development process and to increase development speed.

CakePHP was using Foundation framework for CSS and UI , but they are going to discontinue this associations and will go with the new one i.e. milligram.

Automatic Time zone handling by the ORM if any difference is found between Database timezone and server timezone.

All the deprecated features will be removed completely in new version.

CakePHP will not support PHP 5.6 and PHP 7.0, The minimum version that will be acceptable is PHP 7.1.0. Further It will be modified to PHP 7.2.0 as a minimum acceptable version of PHP.

An improved type-hinting will be added.

Error and warning reporting system is improved.

Validation messages will be embedded in Form helper and date-time input is introduced.

Authentication functionality has been split into standalone plugins Authentication and Authorization.

Spread the love

MVC Web Development Framework

What is Web Development Framework?

There is a huge number of server-side scripting languages, using them we can create web applications. Almost the scripts are full-fledged programming language and featured with Object Oriented Programming Systems. Popular of them are Java, PHP, Python, Ruby,Perl. At the early age of web the applications were built on conventional logic and components, are not organized or not reusable. As the next generation, web development technologies came into existence the requirement of frameworks increased.A need for such a tool was very important as they are time and cost efficient.

Now we have many frameworks with huge communities. Frameworks are the collection of basic building blocks and reusable code in an organized manner where maintenance and development both are painless processes. They implement code re-usability, inheritance, security, abstraction, accessibility, integrity, reliability, readability, maintainability in our applications. Now we are able to develop very robust applications in very less time. frameworks are enriched with various libraries and plugin. They also provide flexibility to extend the functionality of the core. Almost the framework is based on Model-View-Controller or MVC development pattern.

What is MVC?

MVC is a software architectural pattern, which provides a modular structure to an application and application is layered into Models(M), Views(V) and Controllers(C).

MODEL

Model is a layer where all the data building logic is present. This layer is abstract from direct access. We write or database queries and fetch and format data in this layer with given parameters. This layer is a central layer of all three.

VIEW

A view is a presentation layer. We see the desired results here in our browser. The user directly communicates with forms and perform actions and submit inputs. This is an end user layer where HTTP response displayed and request triggered by user actions.

CONTROLLER

A controller is an intermediate layer and create a pool between Model the data logic layer and View the representational layer. It collects user actions based on URI and parameters. Routing and reverse routing happen here.

Advantages of MVC Frameworks:

  1. Fast and quick development of complex web-applications.
  2. Collection of Plugins are available for most of the general purpose activities.
  3. Easy maintenance and debugging. Frameworks provide debugger kit , that eases the debugging process.
  4. MVC provides a modular structure to application that is why MVC based applications are flexible and robust.
  5. Most of them provide Database manipulation library, so no need to write custom and complex queries very often.
  6. Inbuilt security and migration features.
  7. Most of them come with a command-line interface to generate code-snippets and modules.
  8. They create SEO friendly URLs to easy for search engines to recognize your application urls.

What are the popular MVC framework based on PHP?

There are numerous MVC framework based on PHP. Some of them are as:
Laravel – Laravel is the most popular PHP framework with the latest release of PHP and suitable for heavy applications.It comes with Inbuilt Authentication and security features. Laravel has a powerful ORM and query builder. Laravel has a unique feature of artisan CLI tool.Blade template engine is used for presentation on view.

Zend Framework

Created by the developers of PHP.Zend Framework is a collection of professional PHP packages with more than 345 million installations. It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features. Zend Framework uses Composer as a package dependency manager; PHP Unit to test all packages; and Travis CI as a Continuous Integration service. Zend Framework also follows PHP-FIG standards and includes an implementation of PHR-7 for HTTP message interfaces (as shepherded by Matthew Weier O’Phinney, Zend Framework project lead).

CakePHP

CakePHP is a Rapid development framework written in PHP 5.6 and having a unique feature of Naming Convention. CakePHP has a powerful tool of bake console. We can create scaffolding within no time. It is suitable for Web services as well as small and heavy applications. We can use a template engine as well for the presentation layer.

Codeigniter

This is a zero-configuration framework and mostly used for small scale application. It comes with all the features of OOPS and security parameters. It is fast ,and the most flexible among others in a group. Code-igniter has wonderful and organized documentation and a huge community over the web. Codeigniter also provide the feature of HMVC and templating.

Yii

Fastest growing over the internet and popular in recent years. Featured with MVC structure and can be used for small as well as heavy applications. It handles complex WSDL services easily.

Phalcon

Phalcon is a secure and well documented MVC framework. It is suitable for any type of applications. It has implemented with very high-security level.

Spread the love

CakePHP Advance : Most Common Interview Questions and Answers

What is HMAC?
HMAC means Hash-based Message Authentication Code . This is a authentication code used with combination of an encryption key and a hash function.What is Asset.cacheTime ?
Asset.cacheTime sets the asset cache time. This determines the http header Cache-Control’s max-age, and the http header’s Expire’s time for assets.What is DSN?
DSN is Data Source Name. A connection string format that is formed like a URI. CakePHP supports DSN’s for Cache, Database, Log and Email connections.What is PaaS?
Platform as a Service. Platform as a Service providers will provide cloud based hosting, database and caching resources. Some popular providers include Heroku, EngineYard and PagodaBox.

How we can use Cache in CakePHP?
Caching in CakePHP is facilitated by the Cache class. This class provides a static interface and uniform API to interact with various Caching implementations.

What types of Caching Engine does CakePHP provide?
1-FileCache-uses files.
2-ApcuEngine – uses the PHP APCu extension.
3-Wincache – uses the Wincache extension.
4-MemcachedEngine – uses the Memcached extension.
5-RedisEngine – uses the phpredis extension.

What is the default cache file path?
Path to where cache files should be saved. Defaults path is system’s temp dir.

How to read a Cache Object in CakePHP?
Using Cache class we can read the object as given below:

$posts=Cache::read('posts');

How to write a Cache Object in CakePHP?
Using Cache class we can write the object as given below:

    Cache::write('posts',$posts);

How to remove an object completely from Cache?
Using Cache class we can delete the object as given below:

    Cache::delete('posts');

Can we read,write and delete multiple objects at a time?
Yes , we can do cache operations on multiple objects using functions like:

    Cache::deleteMany(['posts','comments','users']);
    Cache::readMany(['posts','comments','users']);
    Cache::writeMany(['posts'=>$posts,'comments'=>$comments,'users'=>$users]);

What is difference between Cache:clear() and Cache::delete() ?
Cache:clear() removes the values from associated with keys and empty them to hold new values, where as Cache:delete() removes the object completely from cache.

How can we disable or enable cache glaoblly in CakePHP?
We don’t need to disable all Cache read & writes and to expiration. We can do this using enable() and disable():

    Cache::disable();
    Cache::enable();

What are the different log levels in CakePHP?
1-Emergency: system is unusable
2-Alert: action must be taken immediately
3-Critical: critical conditions
4-Error: error conditions
5-Warning: warning conditions
6-Notice: normal but significant condition
7-Info: informational messages
8-Debug: debug-level messages

What is CakeRequest?
CakeRequest is the default request object used in CakePHP. By default, CakeRequest is assigned to $this->request, and is available in Controllers, Views and Helpers.

What are different ways to access the parameters in CakePHP?
Following ways :

$this->request->controller;
$this->request['controller'];
$this->request->params['controller'];

How can we access the Passed Argumets from URI in CakePHP?
Way to access the Passed Argumets in CakePHP as:

$this->request->pass;
$this->request['pass'];
$this->request->params['pass'];

How can we access the Named Parameters from URI in CakePHP?
Way to access the Named Parameters in CakePHP as:

$this->request->named;
$this->request['named'];
$this->request->params['named'];

How can we read Query String Parameters?
We can read these paameters using Cake Request Handler :

  // url is as : /posts/index?page=1&sort=title
  $this->request->query['page'];

How can we detect the request type?
We can check any request as :

$this->request->is('post');
$this->request->is('get');
$this->request->is('ajax');
$this->request->is(['put','post']);

How to detect environment in CakePHP?

$this->request->addDetector(
    'post',
    array('env' => 'REQUEST_METHOD', 'value' => 'POST')
);

How to detect pattern value in CakePHP?

$this->request->addDetector(
    'iphone',
    array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i')
);

How to detect options in CakePHP?

$this->request->addDetector('internalIp', array(
    'env' => 'CLIENT_IP',
    'options' => array('192.168.0.101', '192.168.0.100')
));

How to detect callback in CakePHP?

$this->request->addDetector(
    'awesome',
    array('callback' => function ($request) {
        return isset($request->awesome);
    })
);

How to find the root directory of the the application?
$this->request->webroot;

How to find the base path in CakePHP?
$this->request->base;

How to find the full address of the current request in CakePHP?
$this->request->here;

Spread the love

CakePHP Advance Interview Questions and Answers For Experienced and Freshers

(1). What is the default cache Engine in CakePHP?
File Engine is the default cache Engine in Cake PHP.

(2). How many types of cache does CakePHP Support?
Different types of cache supported by CakePHP:
1-FileCache
2-ApcCache
3-Wincache
4-XcacheEngine
5-MemcacheEngine
6-RedisEngine

(3). How mamy types of Associations are there in CakePHP Models?
There are four association types in CakePHP:
Relationship Association type Example
one to one hasOne A user has one profile.
one to many hasMany A user can have multiple recipes.
many to one belongsTo Many recipes belong to a user.
many to many hasAndBelongsToMany Recipes have, and belong to, many ingredients.

(4). How to create association?
Model association example:

class Toy extends AppModel {
    public $hasOne = 'Profile';
    public $hasMany = array(
        'Toy' => array(
            'className' => 'Toy',
            'conditions' => array('Toy.approved' => '1'),
            'order' => 'Toy.created DESC'
        )
    );
}
?>

(5). How to create Pagination in List view?
Cake PHP has a built in component ‘Paginator’. We can use this Component to create Pagination.

(6). How to destroy an association?
Use ‘unbindModel’ to destroy a particular type of association.

$this->Leader->unbindModel(
        array('hasMany' => array('Follower'))
    );

(7). Give an example of LEFT JOIN using CakePHP ORM?
LEFT JOIN example using cake php ORM:

$options['joins'] = array(
    array('table' => 'channels',
        'alias' => 'Channel',
        'type' => 'LEFT',
        'conditions' => array(
            'Channel.id = Item.channel_id',
        )
    )
);
$Item->find('all', $options);

(8). How to prevent the default View and Layout to be rendered?
We can set the default view and default Layout variable to false.

$this->layout='';
$this->autoRender = false;

(9). What is layout in CakePHP?
View files that contain presentational code that wraps many interfaces in your application. Most views are rendered inside a layout.

(10).  What Is A Component In Cakephp?
Components are packages shared between controllers. They are useful when a common logic or code is required between different controllers.

(11). What are Components Used in Cakephp?
1-Security
2-Sessions
3-Access control lists
4-Emails
5-Cookies
6-Authentication
7-Request handling
8-Scaffolding

(12). What Is A Behavior?
Behaviors in CakePHP are associated with Models.Behaviors are used to change the way models behaves and enforcing model to act as something else.

Spread the love

CakePHP Interview Questions and Answers

What is CakePHP ?
CakePHP is an open-source free web framework based on MVC pattern and written in PHP scripting Language for rapid web development.

What is MVC in CakePHP?
Model view controller (MVC) is an architectural pattern used in software engineering.
Model: Handle database related functionality, manipulating database related query like add, edit , delete.
View: Design parts written here (HTML+PHP)
Controller: Business Logic goes here

What are controllers?
A controller is used to manage the logic for a part of your application. Most commonly, controllers are used to manage the logic for a single model. Controllers can include any number of methods which are usually referred to as actions. Actions are controller methods used to display views. An action is a single method of a controller.

List some features of CakePHP framework ?
Top features of CakePHP framework

  1. MVC Architecture
  2. Zero configuration
  3. Inbuilt validation
  4. ACL Functionality and Security
  5. CRUD scaffolding
  6. Easily extendable with plug-ins
  7. Quick and flexible

What are Hooks in CakePHP?
CakePHP hooks are callback functions that are called before or after a model operation and defined in models.
List of some Hooks functions provided by CakePHP.

  1. beforeFind
  2. afterFind
  3. beforeValidate
  4. afterValidate
  5. beforeSave
  6. afterSave
  7. beforeDelete
  8. afterDelete
  9. onError

What is default function for a controller?
function index() is default function in controller.

What is a Element?
Element in cakephp are smaller and reusable bits of view code. Elements are usually rendered inside views.

What Is Scaffolding In Cakephp?
Scaffolding is a technical way that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.

How To Get Current URL In CakePHP?
Simple using the following bit of code:

$this->here;

How can you make urls search engine friendly while using cakephp?
It’s an automatic task that is done by cakephp.

How cakephp URL looks in address bar?
http://example.com/controller/action/param1/param2/param3

What is Composer? How to create a CakePHP Project using Composer?
Composer is a tool for managing project dependencies. You can create a CakePHP project using Composer by running below commands on terminal.

php composer.phar create-project --prefer-dist cakephp/app my_app_name

How To Get Controller Name In CakePHP Views?
Get controller name in CakePHP:

$this->request->params['controller'];

What is a Helper in CakePHP?
Helpers in CakePHP are associated with Presentation layers of application.Helpers mainly contain presentational logic which is available to share between many views, elements, or layouts.

What are are drawbacks of cakephp?.
The learning curve, and it loads full application before it starts your task. Its not recommended for small projects because of heavy structure.

What is the name of Cakephp database configuration file name and its location?
Default file name is database.php.default.
Its located in “/app/config/database.php.defaut”

What is habtm?
Has And Belongs To Many is a kind of associations that can be defined in models for retrieving associated data across different entities.

List some database related functions in cakephp.
find, findAll , findAllBy , findBy , findNeighbours and query.

Spread the love