views:

238

answers:

4

As an MVC newb, I keep getting caught up in the details. One in particular is making me pause longer than I'd expect; pagination. Should pagination go in the model, or in the controller?

In case it matters, I'm using ZF, and would like to paginate the results of some SQL data.

+1  A: 

Logic to paginate goes in the controller. Any data you need, for example the current page number, should go in the model.

When in doubt, data goes in the model and everything that acts on the data goes in the controller.

Tom Cabanski
+5  A: 

Pagination separates records between pages, so it only gathers data from the model, but deals with presentation. Unless it's intrinsic of the model to split the output in multiple pages (which rarely occurs), my suggestion is to put pagination logic (IE dealing with page number) in the controller.

You might also want to consider taking advantage of a view helper, to minimize the code you put into your controller (fat controllers aren't a good thing).

maraspin
+1 for the view helper suggestion.
fireeyedboy
A: 

The controller should handle the parameter for the page number, and then pass it to the model, which will then know which records to retrieve.

For example...

$userModel->getAll((int) $_GET['page']);

(I don't know Zend Framework, but the idea should be clear)

alex
+2  A: 

The thing is though, that Zend_Paginator has a very convenient set of adapters. One of these is Zend_Paginator_Adapter_DbSelect which allows you to enclose a Zend_Db_Select query for efficiently paginating a sql query (e.g. limiting the results). So I can see why you are wondering where to construct these. Although you can indeed debate whether the model is the best place, I personally don't have a problem with creating a method in my model like:

public function fetchEntitiesAsPaginator();

... which would return a Zend_Paginator instance injected with a Zend_Paginator_Adapter_DbSelect.

BTW:
I personally don't consider a paginator just for presentation. I just consider it as a glorified LimitIterator. When you look at it from that perspective, things are starting to look a bit different already. And as a side note: the presentation concerns of Zend_Paginator are seperated by the Zend_View_Helper_PaginationControl view helper already anyway.

fireeyedboy