Caching in an Expression engine addon Caching in an Expression engine addon codeigniter codeigniter

Caching in an Expression engine addon


I once rewrote parts of the CI-caching mechanism. Maybe this can be of any help to you. It is a 'cache' everything function. I wrote it as an override to the system-file.

There is an example of usage in it. It should be very simple. With this code you can cache any functions result, even share between sessions / requests.

http://codeigniter.com/forums/viewthread/221313/

Or this one:

https://github.com/EllisLab/CodeIgniter/issues/1646

If you don't need this new functionality, you can use it as an example on how to use the standard CI caching mechanism.

Like this:

class your_class extends CI_Model{    // ------------------------------------------------------------------------    function __construct( )    {        $cache_adapter = 'apc';        $this->load->driver( 'cache', array( 'adapter' => $cache_adapter, 'backup' => 'dummy' ) );        $this->cache->{$cache_adapter}->is_supported( );    }    // ------------------------------------------------------------------------    public function your_function( $arg )    {        $result = $this->cache->get( __CLASS__ . __METHOD__ . serialize( $arg ) );        if ( empty( $result ) )        {            $result = ... /* your calculation here */            $this->cache->save( __CLASS__ . __METHOD__  . serialize( $arg ) );        }        return $result;    }}

The key I use for the cache is the so called mangled function name. If the result of your function depends solely on its argumens (as it should), you can use it as is. For compactness of the key you could hash it. Like this:

    public function your_function( $arg )    {        $result = $this->cache->get( md5( __CLASS__ . __METHOD__ . serialize( $arg ) ) );        if ( empty( $result ) )        {            $result = ... /* your calculation here */            $this->cache->save( md5( __CLASS__ . __METHOD__  . serialize( $arg ) ) );        }        return $result;    }


Simplest method: instruct your add-on's users to use EE's native tag caching to improve performance. Tag caching works per-EE tag, regardless of user.

Alternately, you can create a database table on install to hold your cached data and use that. Depending of how much and what kind of data you're caching, it could or could not yield performance gains.