Pages

This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Sunday, August 19, 2012

CakePHP Find Query On Associated Model

CakePHP Find Query On Associated Model :-

CakePHP is very flexibile on data mainupulation. CakePHP offer various methods for openration on Model .
Let's start with how to execute find query on Model or We can say Select query on Table :-
First : i am using following tables and use CakePHP 2.x Version.
User Table :
    CREATE TABLE `test`.`users` (
    `id` INT( 5 ) NOT NULL AUTO_INCREMENT ,
    `username` VARCHAR( 40 ) NOT NULL ,
    `password` VARCHAR( 40 ) NOT NULL ,
    `status` ENUM( 't', 'f' ) NOT NULL DEFAULT 't',
    `created` DATETIME NULL ,
    `modified` DATETIME NULL ,
    PRIMARY KEY ( `id` )
    ) ENGINE = InnoDB;

Post Table :
    CREATE TABLE  `test`.`posts` (
    `id` INT( 5 ) NOT NULL AUTO_INCREMENT ,
    `user_id` INT( 5 ) NOT NULL ,
    `title` VARCHAR( 500 ) NOT NULL ,
    `description` TEXT NOT NULL ,
    `created` DATETIME NOT NULL ,
    `modified` DATETIME NULL ,
    PRIMARY KEY (  `id` )
    ) ENGINE = INNODB;

Post Comment Table :
    CREATE TABLE `test`.`post_comments` (
    `id` INT( 5 ) NOT NULL AUTO_INCREMENT ,
    `user_id` INT( 5 ) NOT NULL ,
    `post_id` INT( 5 ) NOT NULL ,
    `comment` VARCHAR( 500),
    `created` DATETIME NULL ,
    `modified` DATETIME NULL ,
    PRIMARY KEY ( `id` )
    ) ENGINE = InnoDB;

Now My Model Struture are as follows:
    class User extends Model
    {
    public $name = array('User');
    public $belongsTo = array('Group');
    public $hasMany = array('Post','PostComment');
    .......
    }

Executing Query On User Model:
If You wish to execute query on User Model then you must include your model name in $uses array
    class YourController extends AppController
    {
    public $uses = array('User','Post','PostComment');
    .......
    }

Now In your action write following code
    class YourController extends AppController
    {
     public $uses = array('User','Post','PostComment');
     .......
     public function getUserDetail($userId=null)
     {
      if(isset($userId) && $userId!=null)
        {
         $result = $this->User->find('first',array('conditions'=>array('User.id'=>$userId)));
         return $result;
        }
        else
        {
         return false;
        }
     }
    }

Above Action will return User detail according to passed userId. Now if you wish to run a query which retrun all users which is belongs to a specific group like "writer" then use following query
    class YourController extends AppController
    {
     public $uses = array('User','Post','PostComment');
     .......
     public function getGroupUsers($groupName=null)
     {
      if(isset($groupName) && $groupName!=null)
        {
         $result = $this->User->find('first',array('conditions'=>array('Group.name'=>$groupName)));
         return $result;
        }
        else
        {
         return false;
        }
     }
    }

We can directly run find query on associated model which has "belongsTo" relationship. but if you wish to execute query on "hasMany" relationship associated Model then use following query
    class YourController extends AppController
    {
     public $uses = array('User','Post','PostComment');
     .......
     public function getUsersByCommentId($commentId=null)
     {
      if(isset($commentId) && $commentId!=null)
        {
         $result = $this->User->find('first',
             array(
                'contain'=>
                  array('PostComment'=>array('conditions'=>array('PostComment.id'=>$commentId)))
                )));
         return $result;
        }
        else
        {
         return false;
        }
     }
    }

Above query will return User details which comment id is equal to passed commentId
If you have any problem place your comment

Sunday, August 12, 2012

How to Apply Auth Component in CakePHP

Auth Component :-

Auth Component allow authentication on our web app. it prevent user to access personal page which required to login into site. Auth basically filter page according to access / prevent policy.
Let start with how to implement Auth Component :-
First : i am using table following table and use CakePHP 2.x Version.
    CREATE TABLE `test`.`users` (
    `id` INT( 5 ) NOT NULL AUTO_INCREMENT ,
    `username` VARCHAR( 40 ) NOT NULL ,
    `password` VARCHAR( 40 ) NOT NULL ,
    `status` ENUM( 't', 'f' ) NOT NULL DEFAULT 't',
    `created` DATETIME NULL ,
    `modified` DATETIME NULL ,
    PRIMARY KEY ( `id` )
    ) ENGINE = InnoDB;

Configuring Components in CakePHP
Step 1:
Auth component is already put inside CakePHP library. so we need to just add into our controller.
Include Auth Component into your controller.
    class YourController extends AppController
    {
    public  $components = array('Auth');
    .......
    }
it could be better to add Auth Component into AppController because it apply to whole web application
    class AppController extends Controller
    {
    
    public  $components = array('Auth');
    .......
    
    }
Step 2:
if you have some other field rather then `username` and `password` then create configure aur settings in beforeFilter() of Controller otherwise skep it.
    function beforeFilter()
    {
        $this->Auth->fields = array(
            'username' => 'YOUR USERNAME FIELD NAME',
            'password' => 'YOUR PASSWORD FIELD NAME'
        );
    }
Step3: 
Setting up login redirect and logout redirect action.
    function beforeFilter()
    {
     $this->Auth->loginRedirect = array('controller' => 'Users', 'action' => 'myaccount');
     $this->Auth->logoutRedirect = array('controller' => 'index', 'action' => 'index');
    }
after above steps your Auth Component is ready to use. now you have to login user using your own logic and add user details into Auth Session.
here i am using my own sample code:-
    public function login()
    {
        if(!empty($this->request->data))
        {
            $username = $this->request->data['User']['username'];
            $password = md5($this->request->data['User']['password']);
            // Fetch User Details from database
            $user = $this->User->find('first',array(          
               'conditions'=> array(
                       'User.username'=>$username,'User.password'=>$password
                            )
              ));
            if(!empty($user))
            {
                $this->Auth->login($user);
                //Redirect To other page
            }
        }
    }
If you have any problem place your comment or follow these link
Authentication
Setting-Auth-Component-Variables
login

Saturday, July 28, 2012

CakePHP Ajax Pagination

CakePHP Ajax Pagination

It's a good practice to use inbuilt design component to build our web application. CakePHP offer many inbuilt component as well as helper.
Ajax Pagination is also a great component / helper to build interactive web application.

To implement Ajax Pagination in your application follow these steps:-
Step1:
 Include RequestHandler component and Js helper in your controller.

    
 public $components = array('RequestHandler');
 public $helpers = array('Js');

Step 2:
Add JQuery library to your current Layout either javascript or cakephp script tag, if already included skip this step.
 echo $this->Html->script('jquery');
Step3:
In your view(ctp) add following line at top most section.
 $this->Paginator->options(array(
      'update' => '#content',
        'evalScripts' => true));

Here we define the div which will update by ajax request and "#content" is id of the div.
Step4:
Now add your  presentation part in view
Step 5:
And at last of your view add following line of code to add javascript to call ajax pagination.
 echo $this->Js->writeBuffer();
If you have any doubt place comment or follow this link
Ajax Pagination