How To Install Configure and Use Memcached in CodeIgniter 3.x.x Ubuntu

codeigniter x memcachedcodeigniter x memcached

Memory object caching systems like Memcached can optimize backend database performance by temporarily storing information in memory, retaining frequently or recently requested records. In this way, they reduce the number of direct requests to your databases.

In this guide, you will learn how to install and configure a Memcached server. You’ll also learn how to add authentication to secure Memcached using Simple Authentication and Security Layer (SASL). Finally, you’ll learn how to bind Memcached to a local or private network interface to ensure that it is only accessible on trusted networks, by authenticated users.

1. Install in Ubuntu

sudo apt-get -y install php8.0-memcached memcached //depend on PHP version

2. Configure the Memcached Memory

vi /etc/memcached.conf

# Start with a cap of 64 megs of memory. It's reasonable, and the daemon default
# Note that the daemon will grow to this size, but does not start out holding this much
# memory
-m 4112

3. Restart Memcached

service memcached restart

4. Use Memcached In CodeIgniter 3.x.x PHP

4a. Check Cache Info

$CI =& get_instance();
$CI->load->driver('cache');
echo '<pre>';
print_r($CI->cache->memcached->cache_info());
echo '</pre>';

4b. Create Cache

$CI =& get_instance();
$CI->load->driver('cache');
$CI->cache->memcached->save('variable', json_encode($array_variable), 60);
// params: 'variable' => cache_key, 
// params: $array_variable => array value content, 
// params: 60 => expired_time_in_second

4c. Get Cache

$CI =& get_instance();
$CI->load->driver('cache');
$array_variable = $CI->cache->memcached->get('variable');
if($cached !== false){
    return json_decode($array_variable, true);
}

4d. Delete Cache

$CI =& get_instance();
$CI->load->driver('cache');
$CI->cache->memcached->delete('variable');

4e. Clear All Caches

$CI =& get_instance();
$CI->load->driver('cache');
$CI->cache->memcached->clean();

References:

User Guide Cache CodeIgniter 2.x.x

User Guide CodeIgniter 3.x.x

Memcached in Magento

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version