Created
June 18, 2012 20:04
-
-
Save scragg0x/2950416 to your computer and use it in GitHub Desktop.
Rediska, Zend_Db, Zend_Db_Select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Cache_Redis { | |
private $_cache; | |
private $_db; | |
private $_tag; | |
private $_key; | |
private $_get; | |
private $_set; | |
function __construct($key=null){ | |
// Cache and Db drivers | |
$this->_cache = Site::get('redis'); | |
$this->_db = Site::get('db'); | |
// Cache get and set methods | |
$this->setStruct(); | |
// Cache key | |
$this->setKey($key); | |
} | |
public function getKey(){ | |
return $this->_key; | |
} | |
public function genKey($sql){ | |
$this->_key = md5($sql); | |
return $this->_key; | |
} | |
public function setKey($key){ | |
$this->_key = $key; | |
} | |
public function setTag($tag){ | |
$this->_tag = $tag; | |
} | |
public function setStruct($struct=null){ | |
switch($struct){ | |
case "hash": | |
$this->_get = 'getHash'; | |
$this->_set = 'setToHash'; | |
break; | |
case "key": | |
default: | |
$this->_get = "get"; | |
$this->_set = "set"; | |
} | |
} | |
public function fetchMethod($fetch, $sql, $bind){ | |
if ($sql instanceof Zend_Db_Select) { | |
$sql = $sql->assemble(); | |
} | |
$key = $this->getKey(); | |
if (!$key){ | |
$params = ""; | |
if ($bind){ | |
if (is_array($bind)){ | |
$params = implode($bind); | |
} else { | |
$params = $bind; | |
} | |
} | |
$key = $this->genKey($sql.$params); | |
} | |
$rows = $this->_cache->{$this->_get}($key); | |
if ($rows === null || $rows === array()){ | |
$rows = $this->_db->$fetch($sql, $bind); | |
$this->_cache->{$this->_set}($key, $rows); | |
if ($this->_tag){ | |
$this->_cache->addToSet($this->_tag, $key); | |
} | |
} | |
return $rows; | |
} | |
public function fetchRow($sql,$bind = array()){ | |
$this->setStruct("hash"); | |
return $this->fetchMethod('fetchRow', $sql, $bind); | |
} | |
public function fetchAll($sql,$bind = array()){ | |
$this->setStruct("key"); | |
return $this->fetchMethod('fetchAll', $sql, $bind); | |
} | |
public function fetchOne($sql,$bind = array()){ | |
$this->setStruct("key"); | |
return $this->fetchMethod('fetchOne', $sql, $bind); | |
} | |
public function reset(){ | |
$this->_tag = $this->_key = null; | |
$this->setStruct(); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment