hairynuggets
hairynuggets

Reputation: 3311

Codeigniter constructor - Load database + set variables

I would like to know how I can add the following code to my codeigniter constructor:

$this->load->model('members_model');
            $member = $this->session->userdata('email_address');
            $viewdata['pagecontent'] = $this->members_model->get_profile($member);

The code is used throughout my controller and it seems silly to repeat it every time. When I try adding it to the constructor I am unable to reference the set variables.

This is the constructor so far:

public function __construct(){
        parent::__construct();  
        Accesscontrol_helper::is_logged_in_super_user();    

        $this->load->model('members_model');
        $member = $this->session->userdata('email_address');
        $viewdata['pagecontent'] = $this->members_model->get_profile($member);
    }

Why wouldn't the above code work? Do constructors require different code?

Upvotes: 0

Views: 2013

Answers (2)

Chris Schmitz
Chris Schmitz

Reputation: 8247

It looks like you are having some scope issues. Since the variables are declared inside of the __construct() method, that is the only method that is able to reference them. You would need to make them class variables in order to have access to them in all of your methods.

Try something like this:

class Your_class extends CI_Controller {

    protected $member;
    protected $viewdata;

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

        Accesscontrol_helper::is_logged_in_super_user();    

        $this->load->model('members_model');

        $this->member = $this->session->userdata('email_address');
        $this->viewdata['pagecontent'] = $this->members_model->get_profile($member);
    }
}

Then you can reference $member and $viewdata in your other methods like this: $this->member

You may want to set this up a little differently, but hopefully you get the idea about variables and scope.

Upvotes: 1

Damien Pirsy
Damien Pirsy

Reputation: 25435

Constructor works, in this sense, like all other methods (and like functions), so your vars are subject to the variable scope.

Do:

class Mycontroller extends CI_Controller {

public $viewdata = array();

    function __construct()
    {
      parent::__construct();
      Accesscontrol_helper::is_logged_in_super_user();
      $this->load->model('members_model');
      // $this->load->library('session');
      // $this->load->database();
      // ^- if not already autoloaded
      $member = $this->session->userdata('email_address');
      $this->viewdata['pagecontent'] = $this->members_model->get_profile($member);
    }
}

Then, in your other controller's methods, you just call the class property $this->viewdata, ex.

function index()
{
  $this->load->view('myview',$this->viewdata);
}

And access it, in myview.php :

echo $pagecontent;

Upvotes: 1

Related Questions