2012-12-10 99 views
0

通过我们的应用程序,我们有非常类似于这样:Zend缓存我们是否需要每次都创建一个新对象?

$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_Cache是​​一个新的对象,并为每个请求这可能最终得到所谓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}"; 
    } 

Magento他们似乎在__construct,那里的Concrete5创建一个静态属性,一旦创建它。

我的问题是什么最好的解决方案?

回答

1

我认为你的getInstance()方法应该返回你的Zend_Cache实例而不是App_Cache。尝试是这样的:

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_Cache实例,然后将其保存在App_Cache对象的 $_instance变量中。

好的,更改了代码以保存Zend_Cache对象的静态实例,并在需要时返回它。这只会创建一次实例。我认为方法名称应该改为getCache()或类似的东西,所以它更清楚它在做什么。

+0

谢谢你,好主意。尽管我得到了:'致命错误:在getFrontend()中不在'对象上下文中'时使用$ this。也有没有办法做到这一点,而不需要改变getInstance中的参数。这已在应用程序代码和以前的项目的许多不同地方引用 –

+0

请参阅上面的编辑。 –

相关问题