2014-02-14 31 views
2

以下是有關高速緩存代理設計模式的問題。帶有PHP的自動對象高速緩存代理

是否可以使用PHP創建一個動態代理緩存實現,以便將緩存行爲自動添加到任何對象?

下面是一個例子

class User 
{ 
    public function load($login) 
    { 
     // Load user from db 
    } 

    public function getBillingRecords() 
    { 
     // a very heavy request 
    } 

    public function computeStatistics() 
    { 
     // a very heavy computing 
    } 
} 

class Report 
{ 
    protected $_user = null; 

    public function __construct(User $user) 
    { 
     $this->_user = $user; 
    } 

    public function generate() 
    { 
     $billing = $this->_user->getBillingRecords(); 
     $stats = $this->_user->computeStatistics(); 

     /* 
      ... 
      Some rendering, and additionnal processing code 
      ... 
     */ 
    } 
} 

你會發現,報告會使用一些重載方法從用戶。

現在我想添加一個緩存系統。 而不是設計一個經典的緩存系統,我想知道是否有可能實現在代理設計模式緩存系統,這種用法:

<?php 
$cache = new Cache(new Memcache(...)); 

// This line will create an object User (or from a child class of User ex: UserProxy) 
// each call to a method specified in 3rd argument will use the configured cache system in 2 
$user = ProxyCache::create("User", $cache, array('getBillingRecords', 'computeStatistics')); 
$user->load('johndoe'); 

// user is an instance of User (or a child class) so the contract is respected 
$report = new report($user) 
$report->generate(); // long execution time 
$report->generate(); // quick execution time (using cache) 
$report->generate(); // quick execution time (using cache) 

每次調用proxyfied方法將運行是這樣的:

<?php 
$key = $this->_getCacheKey(); 
if ($this->_cache->exists($key) == false) 
{ 
    $records = $this->_originalObject->getBillingRecords(); 
    $this->_cache->save($key, $records); 
} 

return $this->_cache->get($key); 

您認爲這是我們可以用PHP做的事嗎?你知道它是否是一種標準模式?你將如何實現它?

這將需要

  • 實現動態的一個新的子類的原始對象
  • 與緩存的一個
  • 實例化更換指定的原始方法,一種新的這個對象的

我覺得PHPUnit和Mock系統做類似的事情...

+0

PHPUnit的使用一些模板和一個eval做...所以很顯然不適合prdo https://github.com/sebastianbergmann/phpunit-mock-objects/blob/master/src/Framework /MockObject/Generator.php#L300 – nemenems

回答

0

您可以在裝飾模式中使用委託並創建一個緩存裝飾器,該緩存裝飾器接受任何對象,然後在通過緩存運行所有對象之後委派所有調用。

這有道理嗎?

+1

主要目標是不編輯緩存的對象 – nemenems

相關問題