Skip to content
Derek Jones edited this page Jul 5, 2012 · 6 revisions

Category:Contributions::Libraries::Miscallenous I have decided to build a versatile caching system for individual variables (as opposed to pages or database queries) in the hopes that it will be useful for somebody looking for something slightly more robust than what is built-in to CodeIgniter (as I was).

Here is the Var_cache Library. It is a very simple idea. If there is some variable that you only want to have the system calculate once a day, or once an hour, or once every 6 minutes, etc., you can do that with this class. It stores certain variables in a table (which is named in a config file and will automatically create for you using CodeIgniter's dbforge library). Each variable has it's own expiration date. When the class is loaded, it pulls the unexpired data from the table and is ready for use.

Here is a usage example:

if (!$count = $this->var_cache->get_var('user_count')) {
    $query = $this->db->query("SELECT COUNT(*) AS count FROM my_users_tbl");
        
    $count = $query->row()->count;
            
    $this->var_cache->set_var('recipe_count',$count);
}

Note, the above example could also be accomplished with CodeIgniter's built-in cache_on() and cache_off() methods, but you can imagine this with many different variable caches, each with different expiration dates or with calculations done on them after being retrieved from the database that you do not want to repeat, etc.


Instructions:

Make the file /system/applications/Var_cache.php:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Var_cache Class
 */
class Var_cache {
    var $vars = array();
    var $table_name = '';
    
    function Var_cache() {
        $this->initialize();
    }
    
    function initialize() {
        $CI =& get_instance();
        
        // Load the table name
        $CI->config->load('var_cache', TRUE);
        
        $config = $CI->config->item('var_cache');
        
        if (!isset($config['var_cache_table_name']))
            show_error("To Use the Var_cache library, the var_cache config file is require");
        
        $table_name = $config['var_cache_table_name'];
        
        $this->table_name = $table_name;
        
        
        // If the table does not exist, make it
        if (!$CI->db->table_exists($this->table_name)) {
            $CI->load->dbforge();
            
            $fields = array(
                'name'=>array(
                    'type'=>'VARCHAR',
                     'constraint'=>255
                 ),
                 'value'=>array(
                    'type'=>'VARCHAR',
                     'constraint'=>255
                 ),
                 'expiration'=>array(
                     'type'=>'DATETIME'
                 )
             );
            
            $CI->dbforge->add_field('id');
            $CI->dbforge->add_field($fields);
            
            $CI->dbforge->create_table($this->table_name,TRUE);
        }
        
        
        // Load variables that have not expired into $this->vars
        $query = $CI->db->get_where($this->table_name,array('expiration >='=>date('Y-m-d H:i:s')));
        
        foreach($query->result() as $var) {
            $this->vars[$var->name] = $var->value;
        }
    }
    
    function get_var($name) {
        return element($name,$this->vars);
    }
    
    // $expiration_time is in minutes
    function set_var($name,$value,$expiration_time=1440) {
        $CI =& get_instance();
        
        $data = array(
            'name'=>$name,
            'value'=>$value,
            'expiration'=>date('Y-m-d H:i:s',time()+$expiration_time*60)
        );
        
        if ($CI->db->get_where($this->table_name,array('name'=>$name))->num_rows())
            $CI->db->update($this->table_name,$data,array('name'=>$name));
        else
            $CI->db->insert($this->table_name,$data);
    }
}

Make the file /system/applications/config/var_cache.php:

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

// The name of the directory where templates are located.
$config['var_cache_table_name'] = 'var_cache';

Finally, to use it load the class with:

$this->load->library('Var_cache');

or use autoload.php

Once loaded, to set a variable:

$this->var_cache->set_var('my_var',$calculated_value,$expiration_in_minutes);

and to get a variable:

$this->var_cache->get_var('my_var');

Note: the values are VARCHAR(255). If you have a need to store larger amounts of data (i.e. pre-parsed text for a web page, etc.), change the table's field "value" appropriately.

Clone this wiki locally