2013-02-15 127 views
0

背景:PHP Memcached扩展OOP实例

我在我的活服务器上安装了PHP Memcached扩展。 尽管多方努力,我似乎​​无法到我的XAMPP发展框内安装Memcached的,所以我依靠下面的代码就可以只实例Memcached的只有Live服务器上:

连接包含在文件每一页:

// MySQL connection here 

// Memcached 
if($_SERVER['HTTP_HOST'] != 'test.mytestserver') { 
    $memcache = new Memcached(); 
    $memcache->addServer('localhost', 11211); 
} 

在我实例化每种方法的那一刻,我不禁想,有一个更好的方式来acheive我的目标,并想知道如果任何人有任何想法?

文件:

class instrument_info { 


    // Mysqli connection 
    function __construct($link) { 
     $this->link = $link;  
    } 

function execute_query($query, $server) { 

    $memcache = new Memcached(); 
    $memcache->addServer('localhost', 11211); 

    $result = mysqli_query($this->link, $query) or die(mysqli_error($link)); 
    $row = mysqli_fetch_array($result); 

    if($server == 'live') 
    $memcache->set($key, $row, 86400); 

} // Close function 


function check_something() { 

    $memcache = new Memcached(); 
    $memcache->addServer('localhost', 11211); 

    $query = "SELECT something from somewhere"; 

    if($_SERVER['HTTP_HOST'] != 'test.mytestserver') { // Live server 

     $key = md5($query); 
     $get_result = $memcache->get($key); 

     if($get_result) {  
      $row = $memcache->get($key);  
     } else { 
      $this->execute_query($query, 'live');   
     } 

    } else { // Test Server 
     $this->execute_query($query, 'prod'); 
    } 

} // Close function 

} // Close Class 

回答

0

我建议您在基于接口的编程和依赖注入阅读起来。以下是一些示例代码,可以让您了解应该如何去做。

interface CacheInterface { 
    function set($name, $val, $ttl); 
    function get($name); 
} 

class MemCacheImpl implements CacheInterface { 
    /* todo: implement interface */ 
} 

class OtherCacheImpl implements CacheInterface { 
/* todo: implement interface */ 
} 

class InstrumentInfo { 
    private $cache; 
    private $link; 

    function __construct($link, $cache) { 
    $this->link = $link; 
    $this->cache = $cache; 
    } 

    function someFunc() { 
    $content = $this->cache->get('some-id'); 
    if(!$content) { 
     // collect content somehow 
     $this->cache->set('some-id', $content, 3600); 
    } 
    return $content 
    } 
} 

define('IS_PRODUCTION_ENV', $_SERVER['HTTP_HOST'] == 'www.my-real-website.com'); 

if(IS_PRODUCTION_ENV) { 
    $cache = new MemCacheImpl(); 
} else { 
    $cache = new OtherCacheImpl(); 
} 

$instrumentInfo = new InstrumentInfo($link, $cache); 

BTW。当涉及到mysqli_query时,你实际上遇到了同样的问题,你的代码依赖于Mysql数据库和mysqli扩展。所有对mysqli_query的调用也应该移出到它自己的类中,代表数据库层。

+0

感谢您的代码,并在正确的方向“推”。我了解这种面向对象方法的必要性,一旦我开始了解它,我将以这种方式开始编码。 – monkey64 2013-02-16 07:33:46