Php Zend cache我们每次都需要创建一个新对象吗?
通过我们的应用程序,我们有一些非常类似的东西:Php Zend cache我们每次都需要创建一个新对象吗?,php,zend-framework,Php,Zend Framework,通过我们的应用程序,我们有一些非常类似的东西: $cache = App_Cache::getInstance()->newObject(300); $sig = App_Cache::getCacheName(sha1($sql)); $res = $cache->load($sig); if ($res === false) { $res = $db->fetchAll($sql); $cache->save($res, $sig); } 目前的问
$cache = App_Cache::getInstance()->newObject(300);
$sig = App_Cache::getCacheName(sha1($sql));
$res = $cache->load($sig);
if ($res === false) {
$res = $db->fetchAll($sql);
$cache->save($res, $sig);
}
目前的问题是,我们每次都会创建一个新的Zend_缓存对象,对于每个请求,这可能会被调用300多次
class App_Cache {
protected static $_instance = null;
public static $enabled = true;
protected $frontend = null;
protected $backend = null;
protected $lifetime = null;
public function __construct() { }
public static function getInstance() {
if (is_null(self::$_instance))
self::$_instance = new self();
return self::$_instance;
}
public function newObject($lifetime = 0) {
return Zend_Cache::factory('Core','Memcached',$this->getFrontend($lifetime),$this->getBackend());
}
public static function getCacheName($suffix) {
$suffix = str_replace(array("-","'","@",":"), "_",$suffix);
return "x{$suffix}";
}
实际上,他们似乎在_构造中创建了一次,在这里,作为Concrete5创建了一个静态属性
我的问题是什么是最好的解决方案 我认为您的
getInstance()
方法应该返回Zend_缓存的实例,而不是App_缓存。试着这样做:
class App_Cache
{
protected static $_instance = null;
protected static $_cacheInstance = null;
public static $enabled = true;
protected $frontend = null;
protected $backend = null;
protected $lifetime = null;
public function __construct() { }
public static function getInstance() {
if (is_null(self::$_instance))
self::$_instance = new self();
return self::$_instance;
}
public function newObject($lifetime = 0) {
if (is_null(self::$_cacheInstance))
self::$_cacheInstance = Zend_Cache::factory('Core','Memcached',$this->getFrontend($lifetime),$this->getBackend());
return self::$_cacheInstance;
}
public static function getCacheName($suffix) {
$suffix = str_replace(array("-","'","@",":"), "_",$suffix);
return "x{$suffix}";
}
}
注意,我将newObject()
方法更改为静态,并将其参数添加到getInstance()
中。通过这种方式,您可以在整个代码中调用getInstance()
,它只会创建Zend\u缓存实例一次,然后将其保存在App\u缓存对象的$\u instance
变量中
好的,将代码更改为保存Zend_缓存对象的静态实例,并在请求时返回它。这将只创建一次实例。我认为应该将方法名更改为getCache()或类似的名称,这样可以更清楚地了解它在做什么 谢谢你,好主意。尽管我从getFrontend()中得到:`致命错误:在不在对象上下文中时使用$this。还有一种方法可以做到这一点,而无需更改getInstance中的参数。这已经在应用程序代码和以前的项目中的许多不同地方被引用