7 * This source file is subject to the new BSD license that is bundled
8 * with this package in the file LICENSE.txt.
9 * It is also available through the world-wide-web at this URL:
10 * http://framework.zend.com/license/new-bsd
11 * If you did not receive a copy of the license and are unable to
12 * obtain it through the world-wide-web, please send an email
13 * to license@zend.com so we can send you a copy immediately.
16 * @package Zend_Paginator
17 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
18 * @license http://framework.zend.com/license/new-bsd New BSD License
23 * @see Zend_Loader_PluginLoader
25 require_once 'Zend/Loader/PluginLoader.php';
30 require_once 'Zend/Json.php';
34 * @package Zend_Paginator
35 * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
36 * @license http://framework.zend.com/license/new-bsd New BSD License
38 class Zend_Paginator
implements Countable
, IteratorAggregate
41 * Specifies that the factory should try to detect the proper adapter type first
45 const INTERNAL_ADAPTER
= 'Zend_Paginator_Adapter_Internal';
48 * The cache tag prefix used to namespace Paginator results in the cache
51 const CACHE_TAG_PREFIX
= 'Zend_Paginator_';
54 * Adapter plugin loader
56 * @var Zend_Loader_PluginLoader
58 protected static $_adapterLoader = null;
65 protected static $_config = null;
68 * Default scrolling style
72 protected static $_defaultScrollingStyle = 'Sliding';
75 * Default item count per page
79 protected static $_defaultItemCountPerPage = 10;
82 * Scrolling style plugin loader
84 * @var Zend_Loader_PluginLoader
86 protected static $_scrollingStyleLoader = null;
91 * @var Zend_Cache_Core
93 protected static $_cache;
96 * Enable or disable the cache by Zend_Paginator instance
100 protected $_cacheEnabled = true;
105 * @var Zend_Paginator_Adapter_Interface
107 protected $_adapter = null;
110 * Number of items in the current page
114 protected $_currentItemCount = null;
121 protected $_currentItems = null;
124 * Current page number (starting from 1)
128 protected $_currentPageNumber = 1;
133 * @var Zend_Filter_Interface
135 protected $_filter = null;
138 * Number of items per page
142 protected $_itemCountPerPage = null;
149 protected $_pageCount = null;
152 * Number of local pages (i.e., the number of discrete page numbers
153 * that will be displayed, including the current page number)
157 protected $_pageRange = 10;
164 protected $_pages = null;
167 * View instance used for self rendering
169 * @var Zend_View_Interface
171 protected $_view = null;
174 * Adds an adapter prefix path to the plugin loader.
176 * @param string $prefix
177 * @param string $path
179 public static function addAdapterPrefixPath($prefix, $path)
181 self
::getAdapterLoader()->addPrefixPath($prefix, $path);
185 * Adds an array of adapter prefix paths to the plugin
189 * $prefixPaths = array(
190 * 'My_Paginator_Adapter' => 'My/Paginator/Adapter/',
191 * 'Your_Paginator_Adapter' => 'Your/Paginator/Adapter/'
195 * @param array $prefixPaths
197 public static function addAdapterPrefixPaths(array $prefixPaths)
199 if (isset($prefixPaths['prefix']) && isset($prefixPaths['path'])) {
200 self
::addAdapterPrefixPath($prefixPaths['prefix'], $prefixPaths['path']);
202 foreach ($prefixPaths as $prefix => $path) {
203 if (is_array($path) && isset($path['prefix']) && isset($path['path'])) {
204 $prefix = $path['prefix'];
205 $path = $path['path'];
208 self
::addAdapterPrefixPath($prefix, $path);
214 * Adds a scrolling style prefix path to the plugin loader.
216 * @param string $prefix
217 * @param string $path
219 public static function addScrollingStylePrefixPath($prefix, $path)
221 self
::getScrollingStyleLoader()->addPrefixPath($prefix, $path);
225 * Adds an array of scrolling style prefix paths to the plugin
229 * $prefixPaths = array(
230 * 'My_Paginator_ScrollingStyle' => 'My/Paginator/ScrollingStyle/',
231 * 'Your_Paginator_ScrollingStyle' => 'Your/Paginator/ScrollingStyle/'
235 * @param array $prefixPaths
237 public static function addScrollingStylePrefixPaths(array $prefixPaths)
239 if (isset($prefixPaths['prefix']) && isset($prefixPaths['path'])) {
240 self
::addScrollingStylePrefixPath($prefixPaths['prefix'], $prefixPaths['path']);
242 foreach ($prefixPaths as $prefix => $path) {
243 if (is_array($path) && isset($path['prefix']) && isset($path['path'])) {
244 $prefix = $path['prefix'];
245 $path = $path['path'];
248 self
::addScrollingStylePrefixPath($prefix, $path);
257 * @param string $adapter
258 * @param array $prefixPaths
259 * @return Zend_Paginator
261 public static function factory($data, $adapter = self
::INTERNAL_ADAPTER
,
262 array $prefixPaths = null)
264 if ($data instanceof Zend_Paginator_AdapterAggregate
) {
265 return new self($data->getPaginatorAdapter());
267 if ($adapter == self
::INTERNAL_ADAPTER
) {
268 if (is_array($data)) {
270 } else if ($data instanceof Zend_Db_Table_Select
) {
271 $adapter = 'DbTableSelect';
272 } else if ($data instanceof Zend_Db_Select
) {
273 $adapter = 'DbSelect';
274 } else if ($data instanceof Iterator
) {
275 $adapter = 'Iterator';
276 } else if (is_integer($data)) {
279 $type = (is_object($data)) ?
get_class($data) : gettype($data);
282 * @see Zend_Paginator_Exception
284 require_once 'Zend/Paginator/Exception.php';
286 throw new Zend_Paginator_Exception('No adapter for type ' . $type);
290 $pluginLoader = self
::getAdapterLoader();
292 if (null !== $prefixPaths) {
293 foreach ($prefixPaths as $prefix => $path) {
294 $pluginLoader->addPrefixPath($prefix, $path);
298 $adapterClassName = $pluginLoader->load($adapter);
300 return new self(new $adapterClassName($data));
305 * Returns the adapter loader. If it doesn't exist it's created.
307 * @return Zend_Loader_PluginLoader
309 public static function getAdapterLoader()
311 if (self
::$_adapterLoader === null) {
312 self
::$_adapterLoader = new Zend_Loader_PluginLoader(
313 array('Zend_Paginator_Adapter' => 'Zend/Paginator/Adapter')
317 return self
::$_adapterLoader;
321 * Set a global config
323 * @param Zend_Config $config
325 public static function setConfig(Zend_Config
$config)
327 self
::$_config = $config;
329 $adapterPaths = $config->get('adapterpaths');
331 if ($adapterPaths != null) {
332 self
::addAdapterPrefixPaths($adapterPaths->adapterpath
->toArray());
335 $prefixPaths = $config->get('prefixpaths');
337 if ($prefixPaths != null) {
338 self
::addScrollingStylePrefixPaths($prefixPaths->prefixpath
->toArray());
341 $scrollingStyle = $config->get('scrollingstyle');
343 if ($scrollingStyle != null) {
344 self
::setDefaultScrollingStyle($scrollingStyle);
349 * Returns the default scrolling style.
353 public static function getDefaultScrollingStyle()
355 return self
::$_defaultScrollingStyle;
359 * Get the default item count per page
363 public static function getDefaultItemCountPerPage()
365 return self
::$_defaultItemCountPerPage;
369 * Set the default item count per page
373 public static function setDefaultItemCountPerPage($count)
375 self
::$_defaultItemCountPerPage = (int) $count;
379 * Sets a cache object
381 * @param Zend_Cache_Core $cache
383 public static function setCache(Zend_Cache_Core
$cache)
385 self
::$_cache = $cache;
389 * Sets the default scrolling style.
391 * @param string $scrollingStyle
393 public static function setDefaultScrollingStyle($scrollingStyle = 'Sliding')
395 self
::$_defaultScrollingStyle = $scrollingStyle;
399 * Returns the scrolling style loader. If it doesn't exist it's
402 * @return Zend_Loader_PluginLoader
404 public static function getScrollingStyleLoader()
406 if (self
::$_scrollingStyleLoader === null) {
407 self
::$_scrollingStyleLoader = new Zend_Loader_PluginLoader(
408 array('Zend_Paginator_ScrollingStyle' => 'Zend/Paginator/ScrollingStyle')
412 return self
::$_scrollingStyleLoader;
418 * @param Zend_Paginator_Adapter_Interface|Zend_Paginator_AdapterAggregate $adapter
420 public function __construct($adapter)
422 if ($adapter instanceof Zend_Paginator_Adapter_Interface
) {
423 $this->_adapter
= $adapter;
424 } else if ($adapter instanceof Zend_Paginator_AdapterAggregate
) {
425 $this->_adapter
= $adapter->getPaginatorAdapter();
428 * @see Zend_Paginator_Exception
430 require_once 'Zend/Paginator/Exception.php';
432 throw new Zend_Paginator_Exception(
433 'Zend_Paginator only accepts instances of the type ' .
434 'Zend_Paginator_Adapter_Interface or Zend_Paginator_AdapterAggregate.'
438 $config = self
::$_config;
440 if ($config != null) {
441 $setupMethods = array('ItemCountPerPage', 'PageRange');
443 foreach ($setupMethods as $setupMethod) {
444 $value = $config->get(strtolower($setupMethod));
446 if ($value != null) {
447 $setupMethod = 'set' . $setupMethod;
448 $this->$setupMethod($value);
455 * Serializes the object as a string. Proxies to {@link render()}.
459 public function __toString()
462 $return = $this->render();
464 } catch (Exception
$e) {
465 trigger_error($e->getMessage(), E_USER_WARNING
);
472 * Enables/Disables the cache for this instance
474 * @param bool $enable
475 * @return Zend_Paginator
477 public function setCacheEnabled($enable)
479 $this->_cacheEnabled
= (bool)$enable;
484 * Returns the number of pages.
488 public function count()
490 if (!$this->_pageCount
) {
491 $this->_pageCount
= $this->_calculatePageCount();
494 return $this->_pageCount
;
498 * Returns the total number of items available.
502 public function getTotalItemCount()
504 return count($this->getAdapter());
508 * Clear the page item cache.
510 * @param int $pageNumber
511 * @return Zend_Paginator
513 public function clearPageItemCache($pageNumber = null)
515 if (!$this->_cacheEnabled()) {
519 if (null === $pageNumber) {
520 foreach (self
::$_cache->getIdsMatchingTags(array($this->_getCacheInternalId())) as $id) {
521 if (preg_match('|'.self
::CACHE_TAG_PREFIX
."(\d+)_.*|", $id, $page)) {
522 self
::$_cache->remove($this->_getCacheId($page[1]));
526 $cleanId = $this->_getCacheId($pageNumber);
527 self
::$_cache->remove($cleanId);
533 * Returns the absolute item number for the specified item.
535 * @param integer $relativeItemNumber Relative item number
536 * @param integer $pageNumber Page number
539 public function getAbsoluteItemNumber($relativeItemNumber, $pageNumber = null)
541 $relativeItemNumber = $this->normalizeItemNumber($relativeItemNumber);
543 if ($pageNumber == null) {
544 $pageNumber = $this->getCurrentPageNumber();
547 $pageNumber = $this->normalizePageNumber($pageNumber);
549 return (($pageNumber - 1) * $this->getItemCountPerPage()) +
$relativeItemNumber;
553 * Returns the adapter.
555 * @return Zend_Paginator_Adapter_Interface
557 public function getAdapter()
559 return $this->_adapter
;
563 * Returns the number of items for the current page.
567 public function getCurrentItemCount()
569 if ($this->_currentItemCount
=== null) {
570 $this->_currentItemCount
= $this->getItemCount($this->getCurrentItems());
573 return $this->_currentItemCount
;
577 * Returns the items for the current page.
579 * @return Traversable
581 public function getCurrentItems()
583 if ($this->_currentItems
=== null) {
584 $this->_currentItems
= $this->getItemsByPage($this->getCurrentPageNumber());
587 return $this->_currentItems
;
591 * Returns the current page number.
595 public function getCurrentPageNumber()
597 return $this->normalizePageNumber($this->_currentPageNumber
);
601 * Sets the current page number.
603 * @param integer $pageNumber Page number
604 * @return Zend_Paginator $this
606 public function setCurrentPageNumber($pageNumber)
608 $this->_currentPageNumber
= (integer) $pageNumber;
609 $this->_currentItems
= null;
610 $this->_currentItemCount
= null;
618 * @return Zend_Filter_Interface
620 public function getFilter()
622 return $this->_filter
;
628 * @param Zend_Filter_Interface $filter
629 * @return Zend_Paginator
631 public function setFilter(Zend_Filter_Interface
$filter)
633 $this->_filter
= $filter;
639 * Returns an item from a page. The current page is used if there's no
642 * @param integer $itemNumber Item number (1 to itemCountPerPage)
643 * @param integer $pageNumber
646 public function getItem($itemNumber, $pageNumber = null)
648 if ($pageNumber == null) {
649 $pageNumber = $this->getCurrentPageNumber();
650 } else if ($pageNumber < 0) {
651 $pageNumber = ($this->count() +
1) +
$pageNumber;
654 $page = $this->getItemsByPage($pageNumber);
655 $itemCount = $this->getItemCount($page);
657 if ($itemCount == 0) {
659 * @see Zend_Paginator_Exception
661 require_once 'Zend/Paginator/Exception.php';
663 throw new Zend_Paginator_Exception('Page ' . $pageNumber . ' does not exist');
666 if ($itemNumber < 0) {
667 $itemNumber = ($itemCount +
1) +
$itemNumber;
670 $itemNumber = $this->normalizeItemNumber($itemNumber);
672 if ($itemNumber > $itemCount) {
674 * @see Zend_Paginator_Exception
676 require_once 'Zend/Paginator/Exception.php';
678 throw new Zend_Paginator_Exception('Page ' . $pageNumber . ' does not'
679 . ' contain item number ' . $itemNumber);
682 return $page[$itemNumber - 1];
686 * Returns the number of items per page.
690 public function getItemCountPerPage()
692 if (empty($this->_itemCountPerPage
)) {
693 $this->_itemCountPerPage
= self
::getDefaultItemCountPerPage();
696 return $this->_itemCountPerPage
;
700 * Sets the number of items per page.
702 * @param integer $itemCountPerPage
703 * @return Zend_Paginator $this
705 public function setItemCountPerPage($itemCountPerPage = -1)
707 $this->_itemCountPerPage
= (integer) $itemCountPerPage;
708 if ($this->_itemCountPerPage
< 1) {
709 $this->_itemCountPerPage
= $this->getTotalItemCount();
711 $this->_pageCount
= $this->_calculatePageCount();
712 $this->_currentItems
= null;
713 $this->_currentItemCount
= null;
719 * Returns the number of items in a collection.
721 * @param mixed $items Items
724 public function getItemCount($items)
728 if (is_array($items) ||
$items instanceof Countable
) {
729 $itemCount = count($items);
730 } else { // $items is something like LimitIterator
731 $itemCount = iterator_count($items);
738 * Returns the items for a given page.
740 * @return Traversable
742 public function getItemsByPage($pageNumber)
744 $pageNumber = $this->normalizePageNumber($pageNumber);
746 if ($this->_cacheEnabled()) {
747 $data = self
::$_cache->load($this->_getCacheId($pageNumber));
748 if ($data !== false) {
753 $offset = ($pageNumber - 1) * $this->getItemCountPerPage();
755 $items = $this->_adapter
->getItems($offset, $this->getItemCountPerPage());
757 $filter = $this->getFilter();
759 if ($filter !== null) {
760 $items = $filter->filter($items);
763 if (!$items instanceof Traversable
) {
764 $items = new ArrayIterator($items);
767 if ($this->_cacheEnabled()) {
768 self
::$_cache->save($items, $this->_getCacheId($pageNumber), array($this->_getCacheInternalId()));
775 * Returns a foreach-compatible iterator.
777 * @return Traversable
779 public function getIterator()
781 return $this->getCurrentItems();
785 * Returns the page range (see property declaration above).
789 public function getPageRange()
791 return $this->_pageRange
;
795 * Sets the page range (see property declaration above).
797 * @param integer $pageRange
798 * @return Zend_Paginator $this
800 public function setPageRange($pageRange)
802 $this->_pageRange
= (integer) $pageRange;
808 * Returns the page collection.
810 * @param string $scrollingStyle Scrolling style
813 public function getPages($scrollingStyle = null)
815 if ($this->_pages
=== null) {
816 $this->_pages
= $this->_createPages($scrollingStyle);
819 return $this->_pages
;
823 * Returns a subset of pages within a given range.
825 * @param integer $lowerBound Lower bound of the range
826 * @param integer $upperBound Upper bound of the range
829 public function getPagesInRange($lowerBound, $upperBound)
831 $lowerBound = $this->normalizePageNumber($lowerBound);
832 $upperBound = $this->normalizePageNumber($upperBound);
836 for ($pageNumber = $lowerBound; $pageNumber <= $upperBound; $pageNumber++
) {
837 $pages[$pageNumber] = $pageNumber;
844 * Returns the page item cache.
848 public function getPageItemCache()
851 if ($this->_cacheEnabled()) {
852 foreach (self
::$_cache->getIdsMatchingTags(array($this->_getCacheInternalId())) as $id) {
853 if (preg_match('|'.self
::CACHE_TAG_PREFIX
."(\d+)_.*|", $id, $page)) {
854 $data[$page[1]] = self
::$_cache->load($this->_getCacheId($page[1]));
862 * Retrieves the view instance. If none registered, attempts to pull f
865 * @return Zend_View_Interface|null
867 public function getView()
869 if ($this->_view
=== null) {
871 * @see Zend_Controller_Action_HelperBroker
873 require_once 'Zend/Controller/Action/HelperBroker.php';
875 $viewRenderer = Zend_Controller_Action_HelperBroker
::getStaticHelper('viewRenderer');
876 if ($viewRenderer->view
=== null) {
877 $viewRenderer->initView();
879 $this->_view
= $viewRenderer->view
;
886 * Sets the view object.
888 * @param Zend_View_Interface $view
889 * @return Zend_Paginator
891 public function setView(Zend_View_Interface
$view = null)
893 $this->_view
= $view;
899 * Brings the item number in range of the page.
901 * @param integer $itemNumber
904 public function normalizeItemNumber($itemNumber)
906 $itemNumber = (integer) $itemNumber;
908 if ($itemNumber < 1) {
912 if ($itemNumber > $this->getItemCountPerPage()) {
913 $itemNumber = $this->getItemCountPerPage();
920 * Brings the page number in range of the paginator.
922 * @param integer $pageNumber
925 public function normalizePageNumber($pageNumber)
927 $pageNumber = (integer) $pageNumber;
929 if ($pageNumber < 1) {
933 $pageCount = $this->count();
935 if ($pageCount > 0 && $pageNumber > $pageCount) {
936 $pageNumber = $pageCount;
943 * Renders the paginator.
945 * @param Zend_View_Interface $view
948 public function render(Zend_View_Interface
$view = null)
950 if (null !== $view) {
951 $this->setView($view);
954 $view = $this->getView();
956 return $view->paginationControl($this);
960 * Returns the items of the current page as JSON.
964 public function toJson()
966 $currentItems = $this->getCurrentItems();
968 if ($currentItems instanceof Zend_Db_Table_Rowset_Abstract
) {
969 return Zend_Json
::encode($currentItems->toArray());
971 return Zend_Json
::encode($currentItems);
976 * Tells if there is an active cache object
977 * and if the cache has not been desabled
981 protected function _cacheEnabled()
983 return ((self
::$_cache !== null) && $this->_cacheEnabled
);
987 * Makes an Id for the cache
988 * Depends on the adapter object and the page number
990 * Used to store item in cache from that Paginator instance
991 * and that current page
996 protected function _getCacheId($page = null)
998 if ($page === null) {
999 $page = $this->getCurrentPageNumber();
1001 return self
::CACHE_TAG_PREFIX
. $page . '_' . $this->_getCacheInternalId();
1005 * Get the internal cache id
1006 * Depends on the adapter and the item count per page
1008 * Used to tag that unique Paginator instance in cache
1012 protected function _getCacheInternalId()
1014 return md5(serialize(array(
1015 spl_object_hash($this->getAdapter()),
1016 $this->getItemCountPerPage()
1021 * Calculates the page count.
1025 protected function _calculatePageCount()
1027 return (integer) ceil($this->getAdapter()->count() / $this->getItemCountPerPage());
1031 * Creates the page collection.
1033 * @param string $scrollingStyle Scrolling style
1036 protected function _createPages($scrollingStyle = null)
1038 $pageCount = $this->count();
1039 $currentPageNumber = $this->getCurrentPageNumber();
1041 $pages = new stdClass();
1042 $pages->pageCount
= $pageCount;
1043 $pages->itemCountPerPage
= $this->getItemCountPerPage();
1045 $pages->current
= $currentPageNumber;
1046 $pages->last
= $pageCount;
1048 // Previous and next
1049 if ($currentPageNumber - 1 > 0) {
1050 $pages->previous
= $currentPageNumber - 1;
1053 if ($currentPageNumber +
1 <= $pageCount) {
1054 $pages->next
= $currentPageNumber +
1;
1058 $scrollingStyle = $this->_loadScrollingStyle($scrollingStyle);
1059 $pages->pagesInRange
= $scrollingStyle->getPages($this);
1060 $pages->firstPageInRange
= min($pages->pagesInRange
);
1061 $pages->lastPageInRange
= max($pages->pagesInRange
);
1064 if ($this->getCurrentItems() !== null) {
1065 $pages->currentItemCount
= $this->getCurrentItemCount();
1066 $pages->itemCountPerPage
= $this->getItemCountPerPage();
1067 $pages->totalItemCount
= $this->getTotalItemCount();
1068 $pages->firstItemNumber
= (($currentPageNumber - 1) * $this->getItemCountPerPage()) +
1;
1069 $pages->lastItemNumber
= $pages->firstItemNumber +
$pages->currentItemCount
- 1;
1076 * Loads a scrolling style.
1078 * @param string $scrollingStyle
1079 * @return Zend_Paginator_ScrollingStyle_Interface
1081 protected function _loadScrollingStyle($scrollingStyle = null)
1083 if ($scrollingStyle === null) {
1084 $scrollingStyle = self
::$_defaultScrollingStyle;
1087 switch (strtolower(gettype($scrollingStyle))) {
1089 if (!$scrollingStyle instanceof Zend_Paginator_ScrollingStyle_Interface
) {
1091 * @see Zend_View_Exception
1093 require_once 'Zend/View/Exception.php';
1095 throw new Zend_View_Exception('Scrolling style must implement ' .
1096 'Zend_Paginator_ScrollingStyle_Interface');
1099 return $scrollingStyle;
1102 $className = self
::getScrollingStyleLoader()->load($scrollingStyle);
1104 return new $className();
1107 // Fall through to default case
1111 * @see Zend_View_Exception
1113 require_once 'Zend/View/Exception.php';
1115 throw new Zend_View_Exception('Scrolling style must be a class ' .
1116 'name or object implementing Zend_Paginator_ScrollingStyle_Interface');