Coding Cheatsheets - Learn web development code and tutorials for Software developers which will helps you in project. Get help on JavaScript, PHP, XML, and more.

Post Page Advertisement [Top]

CakePHP Interview Question and Answer

What is the first file that gets loaded when you run a application using cakephp?
Answer: bootstrap.php
    You can be changed it either through index.php , or through .htaccess
    How to change via webroot > index.php
   
    if (!defined('CAKE_CORE_INCLUDE_PATH')) {
        if (function_exists('ini_set')) {
            ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path'));
        }
        if (!include('Cake' . DS . 'bootstrap.php')) { // Change bootstrap.php file to any file name
            $failed = true;
        }
    } else {
        if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) {
            $failed = true;
        }
    }
   
    How to change through .htaccess
   
    DirectoryIndex test.php
   
Which Function Is Executed Before Every Action In The Controller?
Answer:
Controller::beforeFilter() This function is executed before every action in the controller. It’s a handy place to check for an active session or inspect user permissions.

What Is Scaffolding In Cakephp?

Scaffolding is a technique that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.

How To Add Scaffolding In Your Application?

To add scaffolding to your application,just add the $scaffold variable in the controller,
<?php
class PostsController extends AppController {
var $scaffold;
}
?>

What Is A Component In Cakephp?

Components are packages of logic that are shared between controllers. They are useful when a common logic or code is required between different controllers.

    Include Components In Controller ?
    public $components = array('Session', 'Cookie','Emails');
   
    Loading components In particular action
    App::uses('Common', 'Controller/Component');
    $this->Common = new CommonComponent(new ComponentCollection());
    $this->Common->export($fileName, $headerRow, $data);
   
    Creating a Component
    Create the file in app/Controller/Component/CommonComponent.php
   
    App::uses('Component', 'Controller');
    class CommonComponent extends Component {
        function export($fileName, $headerRow, $data) {
            ini_set('max_execution_time', 1600); //increase max_execution_time to 10 min if data set is very large
            $fileContent = implode("\t ", $headerRow)."\n";
            foreach($data as $result) {
                $fileContent .=  implode("\t ", $result)."\n";
            }
            header('Content-type: application/ms-excel'); /// you can set csv format
            header('Content-Disposition: attachment; filename='.$fileName);
            echo $fileContent;
            exit;
        }
    }
   
    Use it in controller action
    $this->Common->export($fileName, $headerRow, $data);


What is a Helper?
Answer: 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
   
    Include Helpers In Controller ?
    public $helpers = array('Form', 'Html');
   
    Fly Loading Helpers
    To in specific action use below code in that action
    $this->helper[] ="helper_name";

    How to use helper function inside controllers
    App::uses('CommonHelper', 'View/Helper');
    $yourHelper = new CommonHelper(new View());
    pr($yourHelper->getBrowser()); exit;
                OR
    App::import('View/Helper', 'CommonHelper');
    $yourHelper = new CommonHelper(new View());
    pr($yourHelper->getBrowser()); exit;
   
    Creating a new Helper
    Create the file in app/View/Helper/CommonHelper.php
   
    class CommonHelper extends AppHelper {  
        public $helpers = array('Html','Form','Session','Js')
        public function isLoggedIn() {
            if ($this->Session->check('Auth.User.id')) {
                return true;
            } else {
                return false;
            }
        }
    }
   
    Use it in View file    
    If($this->Common->isLoggedIn()){
        // statements
    }
   
   
What Is A Behavior?

Answer: Behaviors in CakePHP are associated with Models.Behaviors are used to change the way models behaves and enforcing model to act as something else.
    Example:
    class Category extends AppModel {
        public $actsAs = array('Tree');
    }
   
    “detach” behaviors from our models at runtime
    $this->Category->Behaviors->unload('Translate');
   
    Create Behavior
    // models/behaviors/soft_deletable.php
    class SoftDeletableBehavior extends ModelBehavior {
        function setup(&$Model, $settings = array()) {
             // do any setup here
        }

        // override the delete function (behavior methods that override model methods take precedence)
        function delete(&$Model, $id = null) {
            $Model->id = $id;

            // save the deleted field with current date-time
            if ($Model->saveField('deleted', date('Y-m-d H:i:s'))) {
                return true;
            }

            return false;
        }

        function beforeFind(&$Model, $query) {
             // only include records that have null deleted columns
             $query['conditions']["{$Model->alias}.deleted <>"] = '';
             return $query;
        }
    }
    Then in your model
    Class User extends AppModel {
        public $actsAs = array('SoftDeletable');
    }
   
    Call Delete method inside controller function 
    function index() {
        $this->User->delete(1); // soft deletes user with id of 1
        $this->User->find('all'); // this will not exclude user with an id of 1
    }

What Is The Use Of $This->Set();

Answer: The set() method is used for creating a variable in the view file.Say for example if we write,
$this->set('posts',$posts); in controller fie, then the variable $posts will be available to use in the view template file for that action.

What Is The Use Of $This->Set(Compact());
Answer: Using $this->set(compact()) , we can pass multiple parameters to access into the view file.
    For example,
    $this->set(compact('posts','users','reports'));
    Now all these variables will be available in respective view file

Which Methods Are Used To Create And Destroy Model Associations On The Fly?
Answer: The bindModel() and unbindModel() Model methods are used to create and destroy model associations on the fly.

    // Let's remove the hasMany...
    $this->Leader->unbindModel(
        array('hasMany' => array('Follower'))
    );
    NOTE: unbindModel only affects the very next // find function.
   
    // Let's use bindModel() to add a new association
    // to the Leader model:
    $this->Leader->bindModel(
        array('hasMany' => array(
                'Principle' => array(
                    'className' => 'Principle'
                )
            )
        )
    );

What Is The Use Of RequestAction Method?

Answer: The method requestAction is used to call a controller’s action from any location and returns data from the action.
    $blogs = $this->requestAction(array('controller' => 'blogs', 'action' => 'index'));
   
    Inside Controller index action
    function index(){
        $conditions = array();
        if ( isset($this->params['author_id'])){
          $conditions['Blog.author_id'] = $this->params['author_id'];
        }

        $blogs = $this->Blog->find('all', array('conditions'=>$conditions);

        if ( isset($this->params['requested']) && $this->params['requested'] == 1){
          return $blogs;
        }
        else{
          $this->set(compact('blogs'));
        }
    }
   
What Is Recursive In Cakephp?
Answer: Recursive is used for depth of the retrieval of records associated with a model data.
By setting recursive, you're forcing Cakephp to only fetch a certain amount of data
   
   
    $this->Author->recursive = -1;
    $authors = $this->Author->find('all');  
    OR
    $this->Author->find('all', array('recursive' =>  -1));
   
    -1 CakePHP fetches Group data only, no joins.
    0 CakePHP fetches Group data and its domain
    1 CakePHP fetches a Group, its domain and its associated Users
    2 CakePHP fetches a Group, its domain, its associated Users, and the Users’ associated Articles

What Is The Default Extension Of View Files In Cakephp?Can We Change It?If Yes Then How?

Answer: Default extension of view files is '.ctp'.
    yes we can change it by writing public $ext = '.yourext'; in AppController.If you want to change it for particular controller then add it into that controller only.You can also change it for the specific action of the controller by putting it in that action of controller.
    public $ext = '.yourext'; in AppController
    - you can change all the views extentions.

    public $ext = '.yourext'; in specific controller like, PostsController
    - you can change all the views extentions of PostsController.

    public $ext = '.yourext'; in specific controller action like, index()
    - you can change the view extention of index.ctp

How Can You Set Custom Page Title For The Static Page?

Answer: To set a custom page title, copy-paste following code anywhere in your static page (.ctp) file:
    $this->set("title_for_layout", "My page title");

Define Callback methods, beforeFilter(), beforeRender(), afterFilter()
Answer:
    beforeFilter() – This function is executed before every action in the controller. It’s a handy place to check for an active session or inspect user permissions.
    beforeRender() – Called after controller action logic, but before the view is rendered. This callback is not used often, but may be needed if you are calling render() manually before the end of a given action.
    afterFilter() – Called after every controller action, and after rendering is complete. This is the last controller method to run.

Define Associations
Answer: CakePhp provides a very powerfull mechanism to handle relation between models ( i.e foreign key relationship between database tables )

The four association types in CakePHP are:
hasOne, hasMany, belongsTo, and hasAndBelongsToMany (HABTM).

belongsTo

If table A has a field that references table B, then table A is said to "belongTo" table B.
When setting up the database table, the foreign key is part of the current model’s table.
Banana belongsTo Apple -> bananas.apple_id

public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );

hasMany:
If table B has a field that references table A, and multiple records in table B can point to the same A record, then table A is said to "hasMany" table B.
A hasMany association will allow us to fetch a user’s comments when we fetch a User record.
hasMany: the other model contains the foreign key.
User hasMany Comment -> Comment.user_id
public $hasMany = array(
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'user_id',
            'conditions' => array('Comment.status' => '1'),
            'order' => 'Comment.created DESC',
            'limit' => '5',
            'dependent' => true
        )
    );

hasAndBelongsToMany (HABTM)
This association is used when you have two models that need to be joined up, repeatedly, many times, in many different ways.
If every record in table A can link to multiple references in table B,
and every record in table B can be linked to by multiple A records, table A is said to "hasAndBelongToMany" table B.

THE TABLES
CREATE TABLE `posts` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `body` text NOT NULL,
  PRIMARY KEY  (`id`)
);
CREATE TABLE `tags` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
);
CREATE TABLE `posts_to_tags` (
  `post_id` int(11) NOT NULL,
  `tag_id` int(11) NOT NULL,
  PRIMARY KEY  (`post_id`,`tag_id`)
);

class Post extends AppModel {
var $name = 'Post';
var $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'Tag',
'joinTable' => 'posts_to_tags',
'foreignKey' => 'post_id',
'associationForeignKey' => 'tag_id',
'with' => 'PostToTag',
),
);

}

No comments:

Post a Comment

Bottom Ad [Post Page]