Skip to content

Instantly share code, notes, and snippets.

@sasezaki
Created January 25, 2016 15:54
Show Gist options
  • Save sasezaki/ef4c40a6c6218874da29 to your computer and use it in GitHub Desktop.
Save sasezaki/ef4c40a6c6218874da29 to your computer and use it in GitHub Desktop.
zend paginator cache renew
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Paginator\Adapter;
use Zend\Cache\Storage\StorageInterface as CacheStorage;
class CacheAdapter implements AdapterInterface
{
/**
* The cache tag prefix used to namespace Paginator results in the cache
*
*/
const CACHE_TAG_PREFIX = 'Zend_Paginator_';
/**
* @var AdapterInterface
*/
private $adapter;
private $adapterCount;
/**
* @var CacheStorage;
*/
private $cache;
public function __construct(AdapterInterface $adapter, CacheStorage $cache, callable $cacheIdentifier = null)
{
$this->adapter = $adapter;
$this->cache = $cache;
if ($cacheIdentifier === null) {
$this->checkAdaperSerializable($adatper);
$cacheIdentifier = function($itemCountPerPage) use ($adapter) {
md5(serialize([$adapter, $itemCountPerPage]));
};
}
$this->cacheIdentifier = $cacheIdentifier;
$this->adapterCount = $adapter->count();
}
private function checkAdaperSerializable($adatper)
{
foreach (get_object_vars($adatper) as $field => $value) {
if(is_object($value)) {
throw new Exception();
}
}
}
public function getItems($offset, $itemCountPerPage)
{
$pageNumber = ($offset === 0 ) ? 1 : $offset / $itemCountPerPage + 1;
$cacheId = $this->getCacheId($pageNumber, $itemCountPerPage);
if ($this->cache->hasItem($cacheId)) {
return $this->cache->getItem($cacheId);
}
$items = $this->adapter->getItems($offset, $itemCountPerPage);
if (!$items instanceof \Traversable) {
$items = new \ArrayIterator($items);
}
$this->cache->setItem($cacheId, $items);
return $items;
}
public function count()
{
return $this->adapterCount;
}
public function clearCache($pageNumber, $itemCountPerPage)
{
$cacheId = $this->getCacheId($pageNumber, $itemCountPerPage);
if ($this->cache->hasItem($cacheId)) {
return $this->cache->removeItem($cacheId);
}
}
protected function getCacheId($pageNumber, $itemCountPerPage)
{
return static::CACHE_TAG_PREFIX . $pageNumber . '_' . $this->getCacheInternalId($itemCountPerPage);
}
/**
* Get the internal cache id
* Depends on the adapter and the item count per page
*
* Used to tag that unique Paginator instance in cache
*
* @return string
*/
protected function getCacheInternalId($itemCountPerPage)
{
return call_user_funct($this->cacheIdentifier, $itemCountPerPage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment