Monday 25 August 2014

Cakephp Caching The best feature

Caching really speeds up your webapp ?

Before go to live your application , things to do:

  • Change debug mode 2 to 0

  •  Configure::write('debug', 2) to Configure::write('debug', 0).  
    
Not only for speed improvement. It is an absolute requirement for every cakephp web Application.

  • Recursive Find statements

It's good feature of Cakephp don't waste you speed only in recursive mode...

Exp: When user have multiple blogs ,if simple use find statement to find user list you will also get all blogs list with users..Means you are getting unuseful data with joins...This really decrease speed of App.
so override default recursive with -1 in AppModel and change whenever you need to change it
 class AppModel extends Model {  
   public $recursive = -1;  
 }  
Use $this->ModelName->find('list'); when need only simple list id & name

  • Get rid of var $uses

 Cutting down on the $uses array helps a little ..
Use loadModel dynamically  whenever it requires
 $this->loadModel('ModelName');  

  • Unbind Models

A good practice is to always specify the fields you need in Find. Also, for spectific queries, you should unbind associated models you don't need.
For Complex queries we can go with query() ...

  • Normalize your database tables

And at last use caching for complex & regulor queries

There are different type of caching cakephp provides..
  1. Filecache
  2. ApcCache
  3. Wincache
  4. XchacheEngine
  5. MemcachEngine
  6. MemcachedEngine
  7. RedisEngine
But in this post i am going with Simple but little bit slow FileCache engine

This is time for an real example of where & how to use Cakephp caching

Exp.
We are going to make a Travel website...
On Home page we have listed most recently added tout packages....
so we know recent tours are dynamic but doesn't changes frequently..so we add latest tours in caching & whenever home page calls we can show them directly from caching no need to make database connection every time...

Code to write cache :
 Cache::write('recent_tours', $recent_tours); //$recent tours contains list of recent tours   

Whenever we need recent_tours list we can access from caching..

 $recent_tours = Cache::read('recent_tours'); //get $recent tours list from caching   

But the problem is how cache will know when admin will add a new tours package ?
Yes Cakephp provide simple Model Callback methods for us to know  this..

 function afterSave(boolean $created, array $options = array()) {  
   //we can update our caching here after add & update records  
 }  
 function afterDelete() {  
   // we can update our caching file after delete records  
 }  



So final code for caching is :

 //Add this code in controller where you need to display recent packages  
 $recent_tours= Cache::read('recent_tours'); // get recent tours if cache avalialbel  
 if(!$recent_tours) { // if cache deleted in model after update records it will create new caching  
           $recent_tours= $this->Tour->find('list',array(  
                fields' => array('name','description')  
         ));  
         Cache::write('recent_tours',$recent_tours);  
 }  


 //Add this code in model for that you writing caching  
 function afterSave($created, $options = Array() ) {  
           Cache::delete('recent_tours');  
 }  
 function afterDelete() {  
         Cache::delete('recent_tours');  
 }  


Here we have used default caching FileCache engine...You can change Cache enging in config/core.php


  Cache::config('default', array(  
            'engine' => 'File', //[required]  
            'duration' => 3600, //[optional]  
            'probability' => 100, //[optional]  
            'path' => CACHE, //[optional] use system tmp directory - remember to use absolute path  
            'prefix' => 'cake_', //[optional] prefix every cache file with this string  
            'lock' => false, //[optional] use file locking  
            'serialize' => true, //[optional]  
            'mask' => 0664, //[optional]  
       ));  



Please don’t forgot to comment you views & errors…It will be helpful to improve this blog..




Thursday 17 July 2014

CakePHP Image upload behavior

CakePHP Image upload behavior

  • Image uploading in webdevelopment  is a very common task, To handle it in Controller is bad habit, because for that we have to write lot of code for creating thumbnails,medium size image, big size image etc .

  • There in  cakephp a Image Behavior is already available for image uploading, which is able to upload images automatically. 

  • Before you start reading Image Behavior , make sure you have codding  knowledge of CakePHP. 

  • In this Image Behavior blog,  I will introduce you Image model Behavior ,how to use it for creating different size images in CakePHP at uploading time by writing just one array code in Model—

Image upload behavior

  • Image Behavior is able to upload image automatically.
  • A simple & special explaination of Image behavior. It will upload Image in afterSave() callback, in the  "app/webroot/img/" folder.

Special notes before go to Image behavior:

  1. It uses file name original  filename .if original file already exists than it uses another name.
  2. It stores file in directory: "app/webroot/img/" + given folder name+/+Image name


Preparation :

  • Download latest cakephp & create a database
  • Download image behaviour(ImageBehavior.php) if it not in you cakephp setup Put image behavout in  “app/model/ Behavior/” 

How to use cakephp image behavoir



1.Create table users

 CREATE TABLE `users` (  
      `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,  
      `email` VARCHAR( 250 ) NOT NULL  
      `file` VARCHAR( 250 ) NOT NULL  
 )  


2.Don’t forget to put ImageBehavour in “app/model/ Behavior/”

3.Create a model for users table in  “app/model” with name User.php


 User.php  
 <?php   
 class User extends AppModel {  
  var $actsAs = array('Containable',  
           'Image' => array(  
                'settings' => array(  
                     'titleField' => 'username',  
                     'fileField' => 'file',   
                     'filedata' =>'filedata',  
                     'defaultFile' => ''),  
                'photos' => array(  
                     'big' => array(  
                          'destination' => 'users',  
                          'size' => 'original',  
                          'type' => 'crop',  
                          'quality' => 100),  
                     'medium' => array(  
                          'destination' => 'users/medium',  
                          'size' => array('width' => 100, 'height' => 90),  
                          'type' => 'resizecrop',  
                          'quality' => 100),  
                     'small' => array(  
                          'destination' => 'users/small',  
                          'size' => array('width' => 52, 'height' => 52),  
                          'type' => 'resizecrop',  
                          'quality' => 100)  
                )  
           )  
 }  
 ?>   

Note: if we will not provide filedata,filename, it will try automatically to detect data[User][filedata] in view & filename field in database..



4.Create controller with name 

 UsersController.php  
 <?php  
 class UsersController extends AppController {  
 function beforeFilter() {  
            parent::beforeFilter();  
           $this->Auth->allow('add');   
 }  
 function add() {  
      if(!empty($this->request->data)) {  
           $this->User->sava($this->request->data); //It will automatically save image with thumbnails & big image..  
      }  
 }  
 ?>  


5.Create View file in add.ctp


 app/view/users/ add.ctp  
 <?php   
      echo $this->Form->create('User',array(‘type’=>’file’,'url' => array('controller'=>'users', 'action'=>’add’)));?>  
      echo $this->Form->input('email',array('type' => 'input'));  
      echo $this->Form->input('filedata',array('type' => 'file',’multiple’=>false))  
      echo $this->Form->input('Submit',array('type' => 'submit'))  
      echo $this->Form->end();  
 ?>  



6.Create Folder for Image save-



 App/webroot/users/medium  
 App/webroot/users/small  


7.Now you can run this small application by  this url
localhost/appname/users/add (assuming you are running application on localhost)

Please don’t forgot to comment you views & errors…It will be helpful to improve this blog..