Skip to main content

Top Cakephp Interview Questions

What is CakePHP?

CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. CakePHP goal is to enable developers to work in a structured and rapid manner–without loss of flexibility. CakePHP takes the monotony out of web development.


CakePHP started in April 2005.When a Polish programmer Michal Tatarynowicz wrote a minimal version of a Rapid Application Framework in PHP, dubbing it Cake.CakePHP version 1.0 released in May 2006.  (source:http://en.wikipedia.org/wiki/CakePHP)


3.4 (on date 2017-04-01).


Model view controller (MVC) is an architectural pattern used in software engineering.
Model      : Database functions exist in the model
View        : Design parts written here
Controller : Business Logic goes here

Here are the requirements for setting up a server to run CakePHP:
An HTTP server (like Apache) with the following enabled: sessions, mod_rewrite (not absolutely necessary but preferred)
PHP 4.3.2 or greater. Yes, CakePHP works great in either PHP 4 or 5.
A database engine (right now, there is support for MySQL 4+, PostgreSQL and a wrapper for ADODB).


How to install CakePHP?

step1: Go to cakephp.org and download the latest version of cakephp.
step2: Cakephp comes in a .zip file,so unzip it.
step3: Extract the files in the localhost in the desired folder (for example:cakephp).
step4: Open the browser and run the URL localhost/cakephp
step5: Just Follow the instructions display on the page.


cakephp/
app/
Config/
Console/
Controller/
Lib/
  Locale/
  Model/
  Plugin/
  Test/
  tmp/
  Vendor/
  View/
  webroot/
    .htaccess
  index.php
  
 lib/
 plugins/
 vendors/
 .htaccess/
 index.php/
 README.md/

Default file name is database.php.default.
Its located at "/app/config/database.php.default".To connect with database it should be renamed to database.php


bootstrap.php
yes it can be changed.Either through index.php , or through .htaccess

- The Security.salt is used for generating hashes.we can change the default Security.salt value in /app/Config/core.php.  
- The Security.cipherseed is used for encrypt/decrypt strings.We can change the default Security.cipherSeed value by editing /app/Config/core.php. 


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.


index() function


function beforeFilter()


  1. Compatible with versions 4 and 5 of PHP
  2. MVC architecture
  3. Built-in validations
  4. Caching
  5. Scaffolding
  6. Access Control Lists and Authentication.
  7. CSRF protection via Security Component.

It loads full application before it starts your task. It's not recommended for small projects because of its resource-heavy structure.


Table names are plural and lowercased,model names are singular and CamelCased: ModelName, model filenames are singular and underscored: model_name.php, controller names are plural and CamelCased with *Controller* appended: ControllerNamesController, controller filenames are plural and underscored with *controller* appended: controller_names_controller.php,


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


To add scaffolding to your application,just add the $scaffold variable in the controller,
<?php
class PostsController extends AppController {
    var $scaffold;
}
?>
Assuming you’ve created Post model class file (in /app/Model/post.php), you’re ready to go. Visit http://example.com/posts to see your new scaffold.


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

  1. Security
  2. Sessions
  3. Access control lists
  4. Emails
  5. Cookies
  6. Authentication
  7. Request handling
  8. Scaffolding

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


  • FormHelper
  • HtmlHelper
  • JsHelper
  • CacheHelper
  • NumberHelper
  • Paginator
  • RSS
  • SessionHelper
  • TextHelper
  • TimeHelper

Behaviors in CakePHP are associated with Models.Behaviors are used to change the way models behaves and enforcing model to act as something else.


Component is a Controller extension, Helpers are View extensions, Behavior is a Model Extension.


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

Layout in cakephp are used to display the views that contain presentational code. In simple views are rendered inside a layout


var $layout = ‘layout_name’;
to overwrite for a specific action use below code in that action
$this->layout =”layout_name”;

public $helpers = array(‘Form’, ‘Html’, ‘Js’, ‘Time’);
to in specific action use below code in that action
$this->helper[] =”helper_name”;

public $components = array(‘Emails’, ‘ImageUploader’, ‘Sms’);

$this->Session->write(‘Bird.Color’, ‘Black’);
$black = $this->Session->read(‘Bird.Color’);
$this->Session->delete(‘Bird’); 

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.

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.

An advantage with first case $this->set('posts', $posts); is that it allows two different names for the view file and controller file. For example, you could write something like $this->set('postData', $posts);. Now the variable name in the view file would be $postData.

The advantage with the second approach $this->set(compact()); is easier to write, and useful especially when we are setting several variables to the view.No need to add separate line for each variable as we have with $this->set();
For example,
$this->set(compact('posts','users','reports'));

Yes its possible.

'email' => array(
    'rule' => array(
        'rule' => 'notEmpty',
        'message' => 'Please Enter Email address.'
    ),
    'rule' => array(
        'rule' => 'email',
        'message' => 'Entered Email address is invalid.'
    )
)

The problem is the first rule notEmpty will never be called because email rule will overwrite it.While using multiple validation rules for the same field you must keep the rule key "unique". In this case if we want to use multiple rules then, we can simple change the rule key names like,
'email' => array(
    'rule1' => array(
        'rule' => 'notEmpty',
        'message' => 'Please Enter Email address.'
    ),
    'rule2' => array(
        'rule' => 'email',
        'message' => 'Entered Email address is invalid.'
    )
)

To get current url in cakephp use, 

echo Router::url($this->here, true);
This will give full URL with hostname.If you want to get relative path instead of full URL,then use the following code:

echo $this->here;
This will produce absolute URL excluding hostname i.e. /controller/abc/xyz/

It's an automatic task that is done by cakephp.

find, findAll , findAllBy , findBy , findNeighbours and query.

The bindModel() and unbindModel() Model methods are used to create and destroy model associations on the fly. 

The method requestAction is used to call a controller’s action from any location and returns data from the action.

How can we use ajax in cakephp?

By calling ajax helper and then using it in controller for rendering.

Has and belongs to many is a kind of associations that can be defined in models for retrieving associated data across different entities.

http://example.com/controller/action/param1/param2/param3

By adding the javascript files in webroot and call them in default views if needed everywhere or just in the related veiws.

There will be two vendor folders available in cakephp frame work.
one in ” app ” folder and one in root folder

The vendor folder in the app folder is used to place the third-party libraries which are application specific.
The vendor folder in the root folder is used to place the third-party libraries which are used for multiple applications.

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 
Note: You cannot specify multiple extensions, however it seems like there is a fall back to .ctp if no .php file is found.

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");

If you want to display the schema of particular model then you just need to add the following single line of code.For example we have “Posts” Controller.
pr($this->Post->schema());

Comments

Popular posts from this blog

How to Create a PDF file in Cakephp 2.0 using Fpdf

Step 1: Download FPDF folder from  http://www.fpdf.org/  . Step 2: Unzip the downloaded Fpdf file and name it “fpdf” or however you require and make sure that you use the same name while calling it. Step 3: Move the “fpdf” unzipped files to  your /app/Vendor directory within Cakephp. Now you should have the directory path as   /app/Vendor/fpdf. Step 4: Create a new Cakephp layout file for the pdfs. We will use this layout when serving a pdf to the client. Create a file called pdf.ctp inside of /app/View/Layouts. Add the following code to /app/View/Layouts/pdf.ctp Layout: /app/View/Layouts/pdf.ctp 1 2 3 4 <?php      header ( 'Content-Disposition: attachment; filename="downloaded.pdf"' ) ;      echo $content_for_layout ; ?> The header function above tells the browser that it is going to receive a file called download.pdf. If you want to change the name

Setup CakePHP Using Xampp On Windows

Step 1: Download XAMPP  and  CakePHP .   Step 2: Install Xampp Once you have installed Xampp (version 1.7.3) on your Windows with the default option, all your files will be located in the C:\xampp folder. Step 3: Mod Rewrite Module Once Xampp is installed as the local server, you can then proceed to enable mod_rewrite. To do so, you will have to open the httpd.conf file that is located in C:\xampp\apache\conf and uncomment by removing # from the following line: # LoadModule rewrite_module modules/mod_rewrite.so Step 4: Place CakePHP Files in a New Folder Extract the CakePHP (version 1.3.8) zip file and copy all its contents to your local web server, which in this instance is C:\xampp\htdocs\cakephp . I have decided to name the CakePHP folder as cakephp, and in it, you will find many files and folders for the framework, including app, cake, docs, vendors, .htaccess, and index.php. Step 5: Set Up Virtual Host Open the httpd-vhosts.conf file from the C:\xampp\apa

Dynamic Sitemap Generation plugin in Cakephp

Here for the SEO implementation we need to generate the sitemap.xml in our application which is accessed by the webmaster tool. So here i am outlined the steps to generate the Xml file . 1. Lets think we have controller by name sitemap,Inside that create an action by name sitemap and paste the following code    public function sitemap(){     $this->layout='ajax';     $this->RequestHandler->respondAs('xml');     $listData = $this->Sitemap->find('all',/*Conditions if you have any*/);     $this->set(compact('listData')); } I through variable $listData to render all data( Keywords,Title,Url,etc ...) that will be shown in sitemap.xml.  This   depends   on the   dynamic link  what   we want to   show  in sitemap.xml.For request handler to work include the RequestHandler component public $components = array('RequestHandler'); Step 2. Create View based on action sitemap On structure MVC as default we need create sitemap.

Druapl 8 Folder and File Permissions

Drupal direcories: find /var/www/html -type d -exec chmod 755 {} \; Drupal files: find /var/www/html -type f -exec chmod 644 {} \; Drupal all content related directories: find /var/www/html/your_site_name/ sites/b2b_cms_mi/files -type d -exec chmod 775 {} \; Drupal all content related files: find /var/www/html/your_project_folder/ sites/default/files -type f -exec chmod 664 {} \; Drupal content folder permission: chmod 777 /var/www/html/your_project_folder/ sites/default/files .htaccess permission cd /var/www/html/your_project_folder/ sites/default/files/config_ fdwgNYChzdnUSBU8hEm-QEe3_ SXdb6kzCJ3ffEC4sB7njFXuK06hHUF OJE888-GN0_gpEE1b0w/sync chmod 777 .htaccess cd /var/www/html/your_project_folder/ sites/default/files/ chmod 777 .htaccess Note:-  your_project_folder is the name of the project. default can be a site folder name, if the application is multisite or else it will be a default folder.