PHP Memcache call in constructor
Im in the process of updating some object models to cache their data to memcache and then fall back to the r开发者_如何学Cegular old sql query if no cache key is found. Originally, the constructors look something like this, though simplified of course.
function __construct($id){
$sql = 'SELECT name, place FROM Objs WHERE ObjID = ?';
$params = array($id);
$data = Database::GetRow($sql, $params);
$this->name = $data['name'];
$this->place = $data['place'];
}
Which I have modified to something like this:
function __construct($id){
$data = $Memcache->get('obj-'.$id);
if(empty($data)){
$sql = 'SELECT name, place FROM Objs WHERE ObjID = ?';
$params = array($id);
$data = Database::GetRow($sql, $params);
$Memcache->set('obj-'.$id, $data, false, 350);
}
$this->name = $data['name'];
$this->place = $data['place'];
}
This is all fine and good, but many of the objects have other private methods that perform other queries and set more attributes. What I'd like to be able to do is have the object in full be returned from memcached, AFTER properties are set. The problem is, I'm not sure how to do this, since the constructor can't assign the $this
keyword.
function __construct($id){
$data = $Memcache->get('obj-'.$id);
if(empty($data)){
$sql = 'SELECT name, place FROM Objs WHERE ObjID = ?';
$params = array($id);
$data = Database::GetRow($sql, $params);
$this->name = $data['name'];
$this->place = $data['place'];
$Memcache->set('obj-'.$id, $data, false, 350);
}else{
//this is definitely not right, though semantically it kinda defines what I want to accomplish
$this = $data
}
}
Is there anyway to keep this logic in the constructor and somehow gracefully have the objected returned from memcached "become" the instance that the constructor receives? Or will I need to alias the constructor within a function that checks memcache first?
精彩评论