PHP Memcached extension OOP instantiation -
background:
i have installed php memcached extension on live server. despite various efforts, can't seem install memcached within xampp development box, relying on next code instantiate memcached on live server:
my connect file included in every page:
// mysql connection here // memcached if($_server['http_host'] != 'test.mytestserver') { $memcache = new memcached(); $memcache->addserver('localhost', 11211); }
at moment instantiating each method, , can't help thinking that there improve way acheive objective , wonder if has ideas?
my class file:
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 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
i suggest read on interface-based programming , dependency injection. here's illustration code might give thought how should go it.
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); } homecoming $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. have same problem when comes mysqli_query, your'e making code dependent on mysql database , mysqli extension. calls mysqli_query should moved out own class, representing database layer.
oop memcached
No comments:
Post a Comment