Nerdblog.pl - Kohana 3 Pagination helper (using Jelly)

Kohana 3 Pagination helper (using Jelly)

Dodano: 01.09.2011

While working on another database-to-html project I realized that 99% of pagination I'm doing is the same fragment of code so I isolated it into a very simple helper:

<?php
class Helper_Pagination
{
	public $pagination, $collection;
 
	public static function factory($jelly, $limit = 10)
	{
		return new Helper_Pagination($jelly, $limit);
	}
 
	public function __construct($jelly, $limit = 10)
	{
		if(is_string($jelly))
		{
			$jelly = Jelly::query($jelly);
		}
 
                $this->pagination = Pagination::factory(array(
                    'current_page'      => array('source' => 'query_string', 'key' => 'page'),
                    'total_items'       => $jelly->count(),
                    'items_per_page'    => $limit,
                ));
 
		$this->collection = $jelly->offset($this->pagination->offset)->limit($limit)->select();
	}
}

Can be quickly converted into standard Kohana's ORM:

<?php
class Helper_Pagination
{
	public $pagination, $collection;
 
	public static function factory($orm, $limit = 10)
	{
		return new Helper_Pagination($orm, $limit);
	}
 
	public function __construct($orm, $limit = 10)
	{
		if(is_string($orm))
		{
			$orm = ORM::Factory($orm);
		}
 
                $this->pagination = Pagination::factory(array(
                    'current_page'      => array('source' => 'query_string', 'key' => 'page'),
                    'total_items'       => $orm->reset(FALSE)->count_all(),
                    'items_per_page'    => $limit,
                ));
 
		$this->collection = $orm->offset($this->pagination->offset)->limit($limit)->find_all();
	}
}
2 komentarze

Xobb

Could you please provide a usage example?

29.11.2011, 13:58

Xobb: it's so straightforward I don't see any need for providing an example, but:

// controller
// $tpl->products = Helper_Pagination('product');

// view (there should be a template system obviously, but you wanted POC)
<?php foreach($products->collection as $product): ?>
<p><?php echo $product->name ?></p>
<?php endforeach; ?>

<?php echo $products->pagination ?>

It's using Pagination module, which was once an official module but for 3.2 version you'll have to look for fork on github. I don't remember whose version I was using here though, sorry.

29.11.2011, 14:03

Podczas komentowania pamiętaj o zachowaniu zasad interpunkcji i ortografii.

Przed dodaniem swojego komentarza przeczytaj dyskusję znajdującą się powyżej. Być może ktoś już napisał to co chcesz powiedzieć lub zostało to wyjaśnione - zadawanie tych samych pytań lub krytykowanie już wyjaśnionych rzeczy jest w złym smaku i niszczy kulturę dyskusji.

Komentarze mają włączony Markdown