views:

515

answers:

1

hello guys,

am working on a project with zend framework and i need your advise on the right way to fetch data from the database.

Am making use of Zend_Layout to load my template. The appropriate view is then loaded into the template.

On the template, there is supposed to be a section that displays data from the database (e.g Categories). Since i am using one template, the data will be displayed on every page requested irrespective of the controller or action called.

I know its not a good practise to fetch the data from the template and it wouldn't be a good idea to fetch the data from each action executed. I dont know if the right thing to do is to use helpers to fetch the data from the database, but wouldn't that go against the whole idea of MVC.

I need advise from you guys.

A: 

You haven't mentioned the option of using a Model class to fetch the data. That's the "M" in MVC. :-)

A Model class is one that has an interface the View can use to request specific fragments of data. Inside the Model class, it may use a mix of using Zend_Db_Table methods, and also custom SQL queries (executed directly through Zend_Db_Adapter's query() method). Whatever works to get the data.

The point is that a Model encapsulates all the logic needed to supply data in a format the View can use.

See also

Bill Karwin
thanks very much for the response. actually when i said fetch data from the database, i meant through the Model class. So u are saying it is okay for me to call the appropriate Model class directly from the template.
War Coder
Yeah. My rule of thumb is that the View can call methods on the Model class, as long as the View treats the Model as effectively 'read-only'. Whether the Model has the data fetched from the database already, or has to run an SQL query at the time the View requests the information, is an implementation detail -- the View shouldn't avoid requesting data it needs based on that.
Bill Karwin