CakePHP and Redis

I recently had to upscale a client’s CakePHP application across multiple front-end web servers on AWS. CakePHP’s file system cache and session storage doesn’t cut it any more. I needed a way of sharing sessions and cached objects. Step in Redis. A centralised, in-memory database, much like memcache – but nicer!

1. Install Redis
On CentOS, I can easily use yum to install Redis.

[codesyntax lang=”bash”]
yum -y install redis

2. Connect PHP and Redis with Predis
This PHP extension is the main connector between PHP and Redis.
Download from https://github.com/nicolasff/phpredis

phpize && ./configure && make && make install

Edit your php.ini file or add a new file into /etc/php.d/ with the following

extension=redis.so

Restart Apache if required.

3. CakePHP changes 
This is the easy part, we only need to edit some parts of your application’s core.php

Firstly, change the value of $engine to Redis

$engine = 'Redis';

Set some basic Redis info

	$prefix = 'some_prefix_';
	$engine = 'Redis';
	$redisServer = 'localhost';
	$redisServerPort = '6379';

Configure a new cache config for Redis

	Cache::config('session', array(
        'engine'    => $engine,
        'server'    => $redisServer,
        'port' 	    => $redisServerPort,
        'prefix'    => $prefix . 'cake_session_',
        'duration'  => '+2 days', // always cache for ages
    ));

Finally configure CakePHP to use Redis sessions.

	// Set session defaults
	Configure::write('Session', array(
        'defaults'      => 'cache',
        'cookie'        => 'A-Cookie-Name',
        'timeout'       => 125,
        'cookieTimeout' => 0,
        'start'         => true,
        'checkAgent'    => false,
        'handler'       => array(
            'config'    => 'session'
        ),
        'engine'        => $engine,
        'server'        => $redisServer,
        'port' 		=> $redisServerPort
    ));

Having done all that, you should be able to test your application and see keys stored in Redis and no file caches stored on the file system, no sessions stored in the database or filesystem.

Run redis-cli and type “KEYS *” to see what CakePHP has saved into Redis.

phpRedisAdmin is a nice web front end to Redis that is well worth a look.

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

3 thoughts on “CakePHP and Redis”

  1. Hi Kieran, Thanks for the great post.
    Have you experienced problem with cakephp shell after changing the config.
    Everything runs fine on my web app, sessions are stored as they should but now I cannot bake or use shell cake, I get a ‘cache engine session is not properly configured’
    Did it happen to you as well?

Leave a Reply

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