TIP: Use Markdown or, <pre> for multi line code blocks / <code> for inline code.
Forums are in read-only mode while we transition to new software.
Tip for caching ORM objects
  • Hi,

    This might be useful for others facing a similar situation I was:

    I wanted to use memcache (or file cache, doesn't matter in this example) to cache ORM objects. Using code like this:


    $this->cache= new Cache();
    $blog = $this->cache->get('blog_id_' . $blog_id);

    if (is_null($blog)) {
    //rebuilding cache
    $blog = ORM::factory('blog',$blog_id);
    $this->cache->set('blog_id_' .$blog_id , $blog);
    }


    I thought that my $blog object would only be re-queried from the db when it wasn't already in the cache. However, when I tested making direct db updates to values in the queried row, these would be reflected in the supposedly cached $blog object, even though the cache itself was not changing (I checked the contents of the file cache and it had no changes)!

    This had me stumped for several hours till I realized its because the caching serializes the object and ORM has a default setting to reload objects when deserialized (ie queries the db again). So to override this, just add to your model (in my example, the Blog_Model):


    protected $reload_on_wakeup = FALSE;


    Now caching of ORM objects works like a dream, at least for me.

    You can also override reload_on_wakeup globally as per Shadowhand's description in this thread. I would also suggest you read his example of when you might run into problems if you decide to override reload on wakeup to FALSE. In my case, it is not an issue and I make sure that I manually clear the cache if my UI or any part of the system is going to update the Blog model.
  • That's a nice way of doing it, although if you need to access the cached object anywhere else you'll have to copy and paste your code again.
    I made some small adjustments to the ORM and ORM_Iterator classes so that you can cache objects from within the model.
  • I've found the easiest solution is to call result_array() and then cache this. Works a charm

    http://docs.kohanaphp.com/libraries/database/result#result_array
  • I have a concern when doing cache for ORM objects

    $this->cache->set('cache_id' , $ORM_OBJECT);

    it caches everything including db connections, passwords.. etc

    in my case I cache hundreds of ORM objects per request. imagine how much memory being wasted.
  • You just need to serialize the ORM object, then it will only cache the data in that actual object. (See the magic sleep and wakeup methods.) Also, it is impossible to cache a database connection, as resources cannot be represented as a string or blob.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion