2011-11-23 36 views
0

我剛剛開始一個小型庫,它需要從各種URLs中篩選scrape並搜索指定的字符串。爲了提高性能,我想要緩存檢索頁面的內容(在請求期間,以便在內存中)。在調試時,我只是傾銷「DATA」到高速緩存中,而不是獲取頁面以提高性能:Singleton-ish模式在CodeIgniter中沒有像預期的那樣工作

我目前得到這個:

class Scraper { 

    private $CI; 
    private $Cache; 


    function __construct() { 
     $this->CI =& get_instance(); 
     $Cache = array(); 
    } 

    public function GetPage($Url) { 
     if(!isset($Cache[$Url])) { 
      dump("Retrieving"); 
      $Cache[$Url] = "DATA";//file_get_contents($Url); 
     } 
     return $Cache[$Url]; 
    } 

    public function FindString($Url, $String) { 
     $Contents = $this->GetPage($Url); 
     $Ret = (strpos(strtolower($Contents), strtolower($String)) !== false); 
     return $Ret; 
    } 
} 

NB。

現在,我有一個循環,它使用相同的URL反覆呼叫FindString()

我希望第一個電話打印出「檢索」,之後,什麼也看不到。實際上,我反覆看到「檢索」。

我懷疑我有一個範圍問題地方 - 無論是庫本身不是單所以每次調用FindString達到唯一的實例 - 或Cache變量被莫名其妙地重新初始化。

有人可以請建議下一步調試。

dump()只是格式化的東西很好對我來說)

回答

2

你缺少你在哪裏訪問實例變量$Cache所有地方的$this。代碼應該是:

class Scraper { 

    private $CI; 
    private $Cache; 


    function __construct() { 
     $this->CI =& get_instance(); 
     $this->Cache = array(); 
    } 

    public function GetPage($Url) { 
     if(!isset($this->Cache[$Url])) { 
      dump("Retrieving"); 
      $this->ache[$Url] = "DATA";//file_get_contents($Url); 
     } 
     return $this->Cache[$Url]; 
    } 

    public function FindString($Url, $String) { 
     $Contents = $this->GetPage($Url); 
     $Ret = (strpos(strtolower($Contents), strtolower($String)) !== false); 
     return $Ret; 
    } 
} 
+2

無法看到樹木的森林。真的很明顯。謝謝 – Basic

相關問題