views:

30

answers:

2

I have a controller with different methods, but they all have to set a variable containing a list of items to be shown in a box in the view, I extract data from the DB and set $data['categories'].
Can I set it once and have it visible by all methods?

+1  A: 

make it a property of the class

class Controller {
    protected $data;

and use '$this' to access in in your methods:

class Controller {
    function foo() {
       $this->data etc...
stereofrog
Yes, it was a silly question. I was doing this but forgot to use `$this->data` instead if just `$data` when loading the view. Thanks.
kemp
+1  A: 

In addition to this, if you are only using $this->data to get the values into your views, instead of doing:

$this->data->something = 'whatever';

Then doing

$this->load->view('something', $this->data);

You can instead set it with:

$this->load->vars('something', 'whatever');

Then later on use the normal localized $data array (or whatever you like) as the variable will be globally available to all loaded view files.

I'm not suggesting either way is better, just letting you know how else it could be done. I personally use a mix of these methods. :-)

Phil Sturgeon
Thanks, I missed load->vars and it's exactly what I needed.
kemp