cakephp titbits usefull development tips

Some of usefull cakephp titbits. These cakephp titbits are for quick reference that are help full while developing the application. These titbits are most commonly used in the development and comes as handy reference.

To get the paths, Url and URL query string

echo $this->request->webroot  will print the webroot directory path.
echo $this->request->base will print the base path.
echo $this->request->here will print the full address to the current request.
echo $this->request->query will print the query string parameters that are passed through URL as query string.

To detect if the current page is the homepage

if ($this->here == $this->webroot){ // this is home page }
or 
if ($this->here == $this->base.'/'){ // this is home page }

To include Element in layout or view

echo $this->element('navbar');

// create the sidebar block. 
$this->start('sidebar'); 
echo $this->element('sidebar/recent_topics');
echo $this->element('sidebar/recent_comments');
$this->end();

To load CSS and JS files in layout

echo $this->fetch(‘css’);
echo $this->Html->css(array(‘forms’, ‘tables’, ‘menu’));
echo $this->fetch(‘script’);
echo $this->Html->css(array(‘forms’, ‘tables’, ‘menu’));

 

Loading vendor files

// Load the class Abc in app/Vendor/Abc.php
App::uses('Abc', 'Vendor');

// To load app/Vendor/abc.php:
App::import('Vendor', 'abc');

//To load app/Vendor/abc/xyz.php:
App::import('Vendor', 'abc/xyz');


To include one controller in another controller

// The same as require('Controller/UsersController.php');
App::import('Controller', 'Users');

// We need to load the class
$Users = new UsersController();

// If we want the model associations, components, etc to be loaded
$Users->constructClasses();

 

Cakephp HtmlHelper functions can be found here

Cakephp FormHelper functions can be found here

 

cakephp login with Email or username

This article “cakephp login with Email or username” will explain how the Auth component will allow user cakephp login with  email or username, instead of using any of username and email address.

Now a days in many application the authentication process is using  either  the username or email with password combination to allow access to the site. In cakephp framework with auth component we can also achieve the same. To allow cakephp login with email or username we need to add some extra code in the app controller which tells the auth component to allow login with either email or username with password combination.

Auth component is used in the cakephp for the process of authentication. It by default allow login with username and password combination. To make auth component  allow cakephp login with email or username we need to add below code in app controller

App controller file will available in “app/controllers” folder with the file name appcontroller.php.

For the combination of

Email + Password
OR
Username + Password

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => array('username', 'email'),'password' => 'password')
            )
        )
    )
);

 

To make auth component  allow cakephp login with only email address we need to add below code in app controller.

For the combination of

Email + Password

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' =>  'email','password' => 'password')
            )
        )
    )
);

 

To make auth component  allow cakephp login with only username we need to add below code in app controller.

For the combination of
Username + Password

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' =>  'username','password' => 'password')
            )
        )
    )
);

cakephp login with Email or username

Cakephp interview questions

Here there are some Cakephp interview questions and answers about How CakePHP Framework works. These cakephp interview questions listed below are  mainly asked in any interview. These cakephp interview questions  are use full both fresher and experienced people.

 

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.

Server requirements for cakephp?

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

Installation of cakephp

01. Go to cakephp.org and download the latest version of cakephp.
02. Cakephp comes in a .zip file so unzip it.
03. Extract the files in the localhost in the desired folder ( lets say cakephp)
04. Open the browser and run the URL localhost/cakephp
05. Follow the instruction showed in the page

what is the folder structure of Cakephp

cakephp/
app/
config/
controllers/
models/
plugins/
tmp/
vendors/
views/
webroot/
.htaccess
index.php
lib/
plugins/
vendors/
.htaccess
index.php
README

List some of the features in Cakephp?

Basic Features List

  1.     Full support of Model, View, Controller Architecture.
  2.     Good Application Scaffolding.
  3.     Very nice Code generation via Bake.
  4.     Helpers for HTML, Forms, Pagination, AJAX, Javascript, XML, RSS and more.
  5.     Access Control Lists and Authentication.
  6.     Router for mapping urls and handling extensions.
  7.     Security, Session, and RequestHandler Components.
  8.     Utility classes for working with Files, Folders, Arrays and more.
  9.     can manage multiple site(apps) developement

Advance Features List

  1.     Internationalization and Localization with static translations in gettext style or dynamic translations of model data.
  2.     Full Console environment with support for multiple tasks. Included shells: bake, schema, acl, i18 extractor, api.
  3.     CSRF protection via Security Component.
  4.     HTTP Authentication via Security Component.
  5.     Flexible Caching: use memcache, apc, xcache, the file system, or a model to speed up your applicationConfigure class to provide dynamic handling of configuration settings and App class to handle importing required classes. Supports Unit Testing (simpletest,unit test)

what is the difference between two vendors folder available in cakephp?

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.

what is the naming convention in cakephp.

According to cakephp naming conventions
1) Table names should be in lowercase and always Plural
2) Model name should be in CamelCased and are always singular eg: ModelName
3) Model file names are also singular and underscored if contains two words eg : model_name.php
4) Controller name should be in CamelCased and are always plural : appended “controller ” eg: ControllerNamesController
5) Controller file names are always plural and underscored : appender “controller” eg: controller_names_controller.php

what is model,view,controller?

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

 

what is a component?
Components in CakePHP are associated with Controllers.
Components are created and used to share common functionality bewteen controllers.

What are commonly used components of cakephp?
1. Security
2. Sessions
3. Access control lists
4. Emails
5. Cookies
6. Authentication
7. Request handling

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

What are commonly used helpers of cakephp?
CacheHelper
FormHelper
HtmlHelper
JsHelper
NumberHelper
Paginator
RSS
SessionHelper
TextHelper
TimeHelper

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.

Difference between Component, Helper, Behavior?
Component is a Controller extension, Helpers are View extensions, Behavior is a Model Extension.

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

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

what is the first function that gets loaded from a controller?
function index()

In which file cake php database configuration is setup ?
“app/config/database.php”

The four model association types in CakePHP are
1) hasOne
2) hasMany
3) belongsTo
4) hasAndBelongsToMany (HABTM).

Database related functions in cakephp.
1) find
2) find(‘first’)
3) find(‘count’)
4) find(‘all’)
5) find(‘list’)
6) find(‘threaded’)
7) query(),
8) save()

How to set layout in the controller?

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

How to including helpers in controller ?

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

How to including components in controller ?

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

Session write, read and delete

1)$this->Session->write(‘Person.eyeColor’, ‘Green’);
2)$green = $this->Session->read(‘Person.eyeColor’);
3)$this->Session->delete(‘Person’);

Which function is executed before every action in the controller?

function beforeFilter()

requestAction is used to ?

To call controller function form view requestAction function is used
$abc = $this->requestAction(‘/controller/action/param:1234’);
// or
$abc = $this->requestAction(‘controller’=>’controller_name’, ‘action’=>’action_name’, ‘param’ => 1234);

what all are drawbacks?

1) The biggest drawback to CakePHP is that it doesn’t completely implement object orientation
2) Can’t be used for small scale apps as it loads the complete application in beginning.
3) The learning curve

php cache engines

PHP Cache Engines

This article will explain all the available cache engines for php. PHP Cache engines are used to implement cache mechanism for the dynamic sites developed using scripting and programming languages. Cache mechanism will help to increase site performance.

CakePHP/PHP comes with several cache engines built-in, and provides an easy system to implement our own caching systems. The built-in caching engines are:

FileCache :

  • File cache is a simple cache that uses local files.
  • Not quite fast and doesn’t provide as many features for atomic operations
  • Concurrent access are not great at all, if several processes try to read/write at the same time
  • since disk storage is often quite cheap, storing large objects, or elements that are infrequently written work well in files

ApcCache  :

  • APC cache uses the PHP APC extension.
  • Really fast
  • Able to provide atomic read/write features
  • But you have less space
  • Uses shared memory on the webserver to store objects and it’s local to each server too

Wincache :

  • Wincache uses the Wincache extension.
  • Wincache is similar to APC in features and performance, but optimized for Windows and IIS.

XcacheEngine :

  • Xcache is a PHP extension that provides similar features to APC.

MemcacheEngine :

  • Uses the Memcache extension.
  • Provides a very fast cache system
  • Can be distributed across many servers, and provides atomic operations

MemcachedEngine :

  • Uses the Memcached extension.
  • It also interfaces with memcache but provides better performance.
  • Quite fast (a bit less than APC ; but still pretty fast)
  • Shared between all your servers : each item has to be cached only once, even if you have several webservers.
  • You can have several servers in your memcached cluster (which means virtually no limit in the size of the cache)

RedisEngine  :

  • Uses the phpredis extension.
  • Redis provides a fast and persistent cache system similar to memcached
  • also provides atomic operations

Read more about Memcache here

set up memcache engine for cakephp

Set up memcache engine for cakephp

Here in this article we are going to see how to set up Memcache Engine for cakephp. Memcached is a Free & open source, high-performance, distributed memory object caching system , generic in nature, but intended for use in speeding up dynamic web applications.

CakePHP comes with several cache engines built-in, and provides an easy system to implement our own caching systems.By default it provides file based caching mechanism which uses local files to store the cached content and is slowest cache engine, and doesn’t provide as many features for atomic operations.

Since the default file engine is very slow there comes the search of alternative cache engines that cackephp provides. one of the most fast search engine that comes in cakephp is Memcache Engine. Below are the steps to set up Memcache Engine for cakephp.

1) Installing the Memcached in operating system.

2) Installing Memcache module/extension for php.

3) Restarting the Apache server.

4) Making Memcache Engine as default engine for cakephp App.

  • Open the bootstrap file which will find in ‘root_folder/app/config/bootstrap.php’
  • Find and replace the code.
Cache::config('default', array('engine' => 'File'));

With

Cache::config('default', array(
    'engine' => 'Memcache',
    'duration' => 3600, // 
    'probability' => 100,
    'prefix' => Inflector::slug(APP_DIR) . '_',
    'servers' => array(
        '127.0.0.1'
    ),
    'persistent' => true,
    'compress' => false,
));

5) Set  Memcache engine as the main caching engine for the app

  • Open the core file which will find in ‘root_folder/app/config/core.php’
  • Find and replace the code.
$engine = 'File';

With

$engine = 'Memcache';

Read more about memcache here

cakephp redirecting to previous page after login

function checkSession() {
// If the session info hasn't been set...
if (!$this->Session->check('User')) {
$this->Session->write('login_referrer',$this->params['url']['url']);
// Force the user to login
$this->redirect('/users/login');
exit();
}
}

 

if ($success) {
if ($this->Session->check(’login_referrer’)) {
$loginReferrer = $this->Session->read(’login_referrer’);
$this->Session->delete(’login_referrer’);
$this->redirect($loginReferrer);
return true;
}
// the line before is the original redirect code
$this->Auth->redirect(’login_success’);
return true;
}

 

echo $this->Html->link('Login', '/login?redirect='.$this->here);

echo $this->Form->input('redirect', array('type' => 'hidden', 'value' => $this->request->query['redirect']));

if (isset($this->request->data['User']['redirect'])) {
    $this->redirect( $this->request->data['User']['redirect'] );
} else {
    $this->redirect( $this->Auth->redirectUrl() );
}

 

simple cakephp file upload functionality.

Here in this article we will discuss about  uploading files in cakephp framework.

Below is a simple cakephp file upload functionality.

Here for the explanation I am considering the Users view and created a new file named upload_file.ctp under app/views/users folder.

Add the below code in upload_file.ctp. This code creates a from for uploading the file with browse button.

<div class="users view">
<h2><?php echo __('User'); ?></h2>
	<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
echo $this->Form->input('pdf_path', array('type' => 'file','label' => 'Pdf'));
echo $this->Form->end('Upload file');
$image_src = $this->webroot.'files/'.$image;
?>
<!-- to display uploaded file ( considering uploaded file is a image) -->
<img src="<?php echo $image_src;?>">
</div>

Since I am using Users view, now  going to use UsersController to handle the uploaded file.

Add the below code in UsersController.php file which is placed in the app/Controllers folder. This code checks the uploaded file for the error and moves the uploaded file to the webroot/files folder.

 public function uploadFile() {
            $filename = '';
            if ($this->request->is('post')) { // checks for the post values
		$uploadData = $this->data['uploadFile']['pdf_path'];
                if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
                    return false;
                }
                $filename = basename($uploadData['name']); // gets the base name of the uploaded file
                $uploadFolder = WWW_ROOT. 'files';  // path where the uploaded file has to be saved
                $filename = time() .'_'. $filename; // adding time stamp for the uploaded image for uniqueness
                $uploadPath =  $uploadFolder . DS . $filename;
                if( !file_exists($uploadFolder) ){
                    mkdir($uploadFolder); // creates folder if  not found
                }
                if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
                    return false;
                } 

            }
           $this->set('image',$filename); 

	}

Note : For explanation I have used User controller and User view. According to the requirement you can any view and controller.