Welcome Guest, Not a member yet? Register   Sign In
How can I use memcache to cache something in Helper function
#1

Now I'm going to create a customized Helper, and in now of its function I want to use memcache to cache something.
So what should I do to use cache like in controller?
Reply
#2

Use the Cache library with the Memcached driver.

Since you said you were building a helper, I've used $CI in place of $this. I've also used getData() and $cacheDuration to represent a generic function and variable rather than $this->getData() and $this->cacheDuration (for a generic method and property) to represent how you get the data to be cached and how long it will be cached, respectively.

PHP Code:
$CI =& get_instance();
$CI->load->driver('cache', array('adapter' => 'memcached'));

$data $CI->cache->get('my_cached_data');
if (! 
$data) {
    // Get the data to be cached.
    $data getData();

    // Set $cacheDuration to the number of seconds you want this data cached.
    $CI->cache->save('my_cached_data'$data$cacheDuration);
}

// Do something with $data... 
Reply
#3

(08-28-2015, 07:55 AM)mwhitney Wrote: Use the Cache library with the Memcached driver.

Since you said you were building a helper, I've used $CI in place of $this. I've also used getData() and $cacheDuration to represent a generic function and variable rather than $this->getData() and $this->cacheDuration (for a generic method and property) to represent how you get the data to be cached and how long it will be cached, respectively.


PHP Code:
$CI =& get_instance();
$CI->load->driver('cache', array('adapter' => 'memcached'));

$data $CI->cache->get('my_cached_data');
if (! 
$data) {
    // Get the data to be cached.
    $data getData();

    // Set $cacheDuration to the number of seconds you want this data cached.
    $CI->cache->save('my_cached_data'$data$cacheDuration);
}

// Do something with $data... 


That is awesome! Now I understand what is get_instance used for. Thanks a lot!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB