Welcome Guest, Not a member yet? Register   Sign In
How do I share data between my Controller's methods?
#1

[eluser]KeyStroke[/eluser]
Hi,

I'm looking for the best way to share common data between a controller's methods. Things like:
1. Logged in state
2. The user id of the person logged in (if any)
3. Date variable

and so on. These are used in almost every method in my application.

So far I've been doing something like this:
Code:
function page_name()
{
   // get the value of common variables through the returned array
   $view_data = $this->_init_common_data();

   /*
      function code goes here
   */

   $this->load->view('view_name', $view_data);
}

function _init_common_data()
{
    $data['logged_in'] = $this->session->userdata('logged_in');
    $data['username'] = $this->session->userdata('username');
    // whatever else here
  
    return $data; // returns an array
}

But this isn't readable nor very practical since I have to call that function with every method I create.

Any suggestions?
#2

[eluser]GSV Sleeper Service[/eluser]
do something like this.
Code:
class foo extends Controller {

    var $data; //declaring this here will make this available to all methods
    
    function method1(){
        $this->data["logged_in"] = true;
    }
    
    function method2(){
        if($this->data["logged_in"]){
            echo "you're logged in!";
        }
    }

}
#3

[eluser]KeyStroke[/eluser]
But where should I instantiate the data? in the constructor of the class?
#4

[eluser]GSV Sleeper Service[/eluser]
yep, in the constructor
#5

[eluser]KeyStroke[/eluser]
Ok thanks. One last question:

Is the constructor called every time one of its methods is called? in other words, will the data in it be instantiated once in a session or every time a method is called?
#6

[eluser]m4rw3r[/eluser]
It is called once per instantiation of the controller, which is every request.
#7

[eluser]KeyStroke[/eluser]
Thank you very much GSV and m4rw3r (man, that's more like a password !!) for your replies. Smile
#8

[eluser]onejaguar[/eluser]
Although it probably isn't as "clean" as setting a global variable for your class, I get tired of writing $this-> all the time so I often just pass the variable as a reference; e.g.:

Code:
function page_name()
{
   $view_data = array();
   $this->_init_common_data($view_data);

   $this->load->view('view_name', $view_data);
}

   // the & before the variable means this is a reference to the
   // original variable, not a copy.
function _init_common_data(&$data)
{
   $data['logged_in'] = $this->session->userdata('logged_in');
   $data['username'] = $this->session->userdata('username');
}




Theme © iAndrew 2016 - Forum software by © MyBB