Skip to content

Instantly share code, notes, and snippets.

@lukemorton
Created September 19, 2011 09:47
Show Gist options
  • Save lukemorton/1226235 to your computer and use it in GitHub Desktop.
Save lukemorton/1226235 to your computer and use it in GitHub Desktop.
Dealing with pagination in MVVM
<?php
class Controller_News {
public function action_category()
{
$category = ORM::factory('news_category', array('url' => $this->request->param('category')));
if ( ! $category->loaded())
{
throw new HTTP_Exception_404;
}
$view = new View_News_Category;
$view->category = $category;
$view->pagination = new View_Pagination(
$category->count_articles(), // A new method you write in Model_News_Category
5,
$this->request->query('page'));
$this->response->body($view);
}
}
<?php
class View_News_Category extends Kostache {
// This is the partial that will access
// View_News_Category::pagination() provided data
protected $_partials = array('pagination' => 'shared/_pagination');
protected $category;
protected $pagination;
protected $articles;
protected function _articles()
{
if ($this->articles === NULL)
{
$this->articles = $this->category->articles
->where('enabled', '=', 1)->articles
->limit($this->pagination->get_limit())
->offset($this->pagination->get_offset())
->find_all();
}
return $this->articles;
}
public function articles()
{
$return = array();
foreach ($this->_articles() as $row)
{
$return[] = array
(
'location' => '',
'title' => $row->name,
'summary' => $row->summary,
);
}
return $return;
}
public function pagination()
{
// Just returns the object and would be referenced in
// the template like:
// {{#pagination}}
// {{>pagination}}
// {{/pagination}}
//
return $this->pagination;
}
}
<?php
class View_Pagination { // Does not extend Kostache
// This class would contain all the logic currently
// contained within the Pagination class. The data
// would be provided in a Mustache friendly format
// for use in mustache or other templates.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment