1

Is it possible to add the following code to multiple functions 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.

5 Answers 5

2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I'm just wondering why are you using protected and not private ?
Hah - sorry I meant private! Need sleep :)
Heh no problem :) I was just thinking if protected offers a greater advantage.
1

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();

Comments

0

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

1 Comment

thanks I tried but I get Cannot access empty property for both
0

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

2 Comments

Thanks, I had tried putting the code in constructor but I get undefined variable for $user_id wherever I try to use it in controller functions.
Check the change to the example, use $this->user_id in any of the controller functions you are looking to use it in, and then $row in any of the views. Is that what you're looking to do?
-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.