I'm building an add-on for ExpressionEngine 2.x
and I'd like to cache some data on the server. Specifically, I'd like to cache the result of parsing a template so I don't have to parse it again for the same request.
At the moment I'm using $_SESSION
, but that only caches for that user. Ideally, I'd like to store the cache for everyone in memory or on disk. I've also tried $this->EE->session->cache
, but that only caches for the current request. I've had a look at the caching driver for CodeIgnitor, but I'm not sure how I can get it working from within my add-on in ExpressionEngine: http://codeigniter.com/user_guide/libraries/caching.html
I could also go with using Memcache
or writing to a file, but as it needs to work on lots of different setups, there's no guarantee Memcache will be installed or there will be any writable folders.
Any ideas?
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;
}