2012-12-10 30 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

請參閱上面的編輯。 –

相關問題