开发者

Codeigniter pass variables to to multiple controller functions

Is it possible to add the following code to multiple function开发者_开发百科s without retyping the code individually?

$user_id = $this->tank_auth->get_user_id();
$data['row'] = $this->Profile_model->profile_read($user_id);

I tried putting the variables in the constructor but I get undefined variables for both.


you could turn it in to a private function of the controller, i.e.

private function get_user_id()
{
    $user_id = $this->tank_auth->get_user_id();
    return $this->Profile_model->profile_read($user_id);
}

And then in every function in your controller do:

$data['row'] = $this->get_user_id();


It only saves you one line but thats a 100% decrease in code lines!

private function rowData(){
  $user_id = $this->tank_auth->get_user_id();
  return $this->Profile_model->profile_read($user_id);
}

$data['row'] = $this->rowData();


Well if you put it in the constructor you'd need:

$this->user_id = $this->tank_auth->get_user_id();
$this->data['row'] = $this->Profile_model->profile_read($user_id);


You can have this as the controller's constructor:

class Example extends CI_Controller {

   protected $user_id;

   function __construct()
   {
        parent::__construct();

        $this->load->library('tank_auth');
        $this->load->model('Profile_model');

        $this->user_id = $this->tank_auth->get_user_id();
        $data['row'] = $this->Profile_model->profile_read($this->user_id);

        $this->load->vars($data);
   }

}

and you will have access to $row in any subsequent views loaded from that constructor, as well as be able to use $this->user_id in any of the functions of that controller.

Source: http://codeigniter.com/user_guide/libraries/loader.html


Did you load the tank_auth library or set it to autoload?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜