views:

40

answers:

2

If I want to gather some data from the database and use it in multiple actions of a controller, how would I do this?

Currently I just access the model and retrieve the data separately in each action (yes, I know this is inefficient... it's why I'm asking you all!):

public function indexAction()
{
    $model = $this->_getStuffModel();
    $this->view->results = $model->fetchEntries();
}

public function anotherAction()
{
    $model = $this->_getStuffModel();
    $foo = $model->fetchEntries();
    foreach($foo as $k => $v)
    {
        //manipulate the data
    }
    $this->_helper->json($theoutput);
}

If I were not doing this in Zend Framework I would just put it in the constructor and then be good to go with $this->whatever in any method of the object but I don't see how to do this in ZF (I tried sticking it in init() but it didn't work... maybe I just made a stupid coding error and that is actually the correct place to do this?).

*EDIT: If I have, say, 7 actions in a controller and I put the code that hits the database in the init() method then I will hit the database with each and every action that is called. That won't do.

+2  A: 

The init() Action is called on every request against the controller. If you do:

protected $model;

public function init()
{
    $this->model = $this->_getstuff();
}

public function indexAction()
{
   echo $this->model->name;
}

than it should work.

ArneRie
As the init() is called each time, remember it is not more efficient than putting the '$this->_getstuff()' function in each ...Action() method, it just prevents you from repeating yourself which is a good practice.
Roalt
Not repeating is good but not making multiple trips to the database would be better. Do you know how?
rg88
@ArneRie - this solves making it work in the init() action but, as it is called before every action it doesn't solve the problem of using retrieved data multiple times off of one database request. Perhaps the only solution is to stick the database results into the registry?
rg88
You could store the result/object inside the session
ArneRie
+1  A: 

I think the @ArneRie init() solution is what you want. Another solution will be to cache the Zend_Db_Rowset object with all the entries using Zend_Cache and serve it from cache. You can hit the database only when new data is added ( and the save function can register an observer that will delete related cache entries), or maybe each 10 minutes ( and you check the timestamp of the cache entry) or another business logic of your choosing.

Elzo Valugi