随着业务的进展,现在需要直接操作Redis 数据!
其中就需要获取指定前缀的key,就好像操作mysql一样,需要获取指定记录段!
ZF2强大的支持了redis缓存方式,但是当我运用 ZF2 redis缓存 工厂模式的时候,竟然发现ZF2不支持 redis的keys 方法!
//感谢博主:http://my.oschina.net/cart/
接下来给大家详述如何扩展ZF2 Redis:
\module\Application\src\Application\Service\RedisExtendService.php
<?php
namespace Application\Service;
use Zend\Cache\Storage\Adapter\Redis;
class RedisExtendService extends Redis
{
public function __construct($options = null)
{
parent::__construct($options);
}
/**
* support regular
*
* @param sting $keys
*/
public function getKeys($keys)
{
return $this->getRedisResource()->keys($keys);
}
}
OK,扩展完毕!
indexAction中直接使用我们扩展好的ZF2 Redis,只要你乐意扩展,不想局限于ZF2,那么你就可以使用很多Redis原始方法:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
private static $redis;
private function redis(){
if(!self::$redis){
$config = $this->getServiceLocator()->get('config');
self::$redis = new \Application\Service\RedisExtendService($config['Redis']);
}
return self::$redis;
}
public function indexAction(){
var_dump($this->redis()->getKeys('Member_*'));
var_dump($this->redis()->getKeys('Item_*'));
var_dump($this->redis()->getKeys('Product_*'));
}
}
有了此文,大家可以举一反三,大量的继承扩展ZF2!
而且你的扩展是高效,可移植的!