Searching...
Tuesday, April 10, 2012

How to call component's in controller in cakephp 2.0

How to call component's in controller in cakephp 2.0 

Component in cakephp gives you imense power to reuse your general function like if you want user_id in your every controller then you need to write the same code in every controller as you cant access the private function of any controller so, here components serve you in a humble manner for e.g I need a function which returns user_id from a user table 

Here we go for a component 

<? php 
class UserComponent extends Component{
        var $controller;
       public $components = array('Session'); // you can call another component like this 
protected $default_model = 'User'; 
        # As we are using User component , so default One will be 'User'
//called before Controller::beforeFilter()
function initialize(&$controller, $settings = array()) { 
// saving the controller reference for later use 
$this->controller =& $controller;
$this->request = $this->controller->request;
               /* you cant access requested data as this->request->data in component thats why ,you have to access it through the controller */

}

// you can further use it for some other logic which you want to execute after before filter 
//called after Controller::beforeFilter() 
// function startup(&$controller) { 
// }
  
      function get_user_id(){

           $this->controller->loadModel($this->default_model);
           // here i am going to use my silly logic :)  i will get the id through name considering name as a unique    field 
            $var = "furqan";
            $id = $this
->controller
->{$this->default_model}
->field('user_id' 
,array('name' => $var)
);
  return  $id;
     }




}
?>

To call this component in any controller 
<?php
class UsersController extends AppController {

var $components = array('User');

function index(){

$id = $this->User->get_user_id();

debug($id);


}

?>
hopefully everything works fine :)


0 comments:

 
Back to top!