Welcome Guest, Not a member yet? Register   Sign In
Using CI cache only when there's no session
#1

[eluser]Unknown[/eluser]
Hi everyone!

I'd been searching the forum how to use codeigniter's cache only when there is no session but I didn't find anything useful.
I made this code with hooks that solves my problem and I hope this can be useful for other people.

hooks/MYCache.php
Code:
<?php

class MYCache
{
    
    function display_cache_override()
    {
        /*
         * Do nothing at this stage
         */
    }
    
    function post_controller_constructor_cache()
    {
        $CI = &get;_instance();
        
        $CFG =& load_class('Config');
        $URI =& load_class('URI');
        $OUT =& load_class('Output');
        //Don't use cache if we have session
        if(!$CI->session->userdata('current_user_id'))
        {
            if ($OUT->_display_cache($CFG, $URI) == TRUE)
                exit;
        }
    }
}

config/hooks.php
Code:
$hook['post_controller_constructor'] = array(
    'class'    => 'MYCache',
    'function' => 'post_controller_constructor_cache',
    'filename' => 'MYCache.php',
    'filepath' => 'hooks',
    'params'   => array()
);

$hook['cache_override'] = array(
    'class'    => 'MYCache',
    'function' => 'display_cache_override',
    'filename' => 'MYCache.php',
    'filepath' => 'hooks',
    'params'   => array()
);

This hooks overrides the CI's cache calling it later, when we already have the $CI object so we can check the session among other things.
You also need to enable hooks in config.php.
With this. you can use CI's cache as usual.
Have fun!

(EDITED)
I forgot to say that you need to be careful calling $this->output->cache(); do it only if you're sure that there is no session!! Smile
#2

[eluser]skunkbad[/eluser]
I'd be curious to know if this slows down the serving of the cached html compared to standard cache usage. Also how this compares to not caching at all. Is it worth it?
#3

[eluser]Unknown[/eluser]
Hi skunbad,
Between the cache hook and the post_contoller_constructor hook Codeigniter the following classes: Input, Language, Loader, Controller, your controller and calls all the constructors. I suppose that is not as fast as the original cache, and it depends in what you do in the controller's constructor (I.E., fetching the user from the database).
In fact is almost like doing cache logic at the begining of the controller's method.
Sorry but I don't have satisfactory benchmarks either with the original and my version of the cache, I'm always getting mixed results Big Grin




Theme © iAndrew 2016 - Forum software by © MyBB