【问题标题】:Singleton-ish pattern not working as expected in CodeIgniter单例模式在 CodeIgniter 中无法按预期工作
【发布时间】:2011-11-24 03:31:46
【问题描述】:

我刚刚创建了一个小型库,它需要筛选来自各种 URL 的抓取并搜索指定的字符串。为了提高性能,我想缓存检索到的页面的内容(在请求期间,所以在内存中)。

我目前有这个:

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;
    }
}

注意:为了提高调试时的性能,我只是将“DATA”转储到缓存中,而不是获取页面。

现在,我有一个循环使用相同的 URL 重复调用 FindString()

我希望第一次调用会打印出“检索”,然后就什么也看不见了。事实上,我反复看到“检索”。

我怀疑我遇到了范围问题某处 - 要么库本身不是单例,所以每次调用 FindString 都会到达一个唯一的实例 - 或者 Cache 变量正在以某种方式重新初始化。

有人可以建议接下来的调试步骤吗?

dump() 只是为我很好地格式化东西)

【问题讨论】:

    标签: php codeigniter caching


    【解决方案1】:

    您在访问 instance 变量$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;
        }
    }
    

    【讨论】:

    • 只见树木不见森林。确实很明显。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2012-12-26
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多