1

Im in the process of updating some object models to cache their data to memcache and then fall back to the regular 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?

hakre
  • 193,403
  • 52
  • 435
  • 836
DeaconDesperado
  • 9,977
  • 9
  • 47
  • 77
  • 1
    You should decouple your classes. You should have different objects for data representation, different objects for building the first ones from database queries results and different objects for implementing the caching mechanism so you can easily re-use them in different context. Try to look at some ORM, for example Doctrine 2. – Ondřej Mirtes Jun 16 '11 at 20:05
  • Try to read excellent articles from Miško Hevery for starters: http://misko.hevery.com/code-reviewers-guide/ – Ondřej Mirtes Jun 16 '11 at 20:06
  • I wonder how this line does not throw something: $data = $Memcache->get('obj-'.$id); Where is $Memcache initialized? – kodeart Dec 20 '12 at 18:16

0 Answers0