Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Redis/Memcached php wrapper with callbacks

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 README.md
Octocat-spinner-32 redmem.php
Octocat-spinner-32 tests.php
README.md

RedMem cache wrapper

If you do not know which tool is best to use for caching in your project (Memcache or Redis) you can use RedMem simple wrapper.

Installation

Just copy and include redmem.php include 'redmem.php'

PHP 5.3 or 5.3+ required

Connecting

Connection options for Redis:

 array(
  'server'        => '127.0.0.1',
  'port'          => 6379,
  'timeout'       => 0,
  'persistent'    => true
 );   

Connection options for Memcache:

 array(
  'servers'        => array('127.0.0.1:11211'),
  'persistent'    => true
 );      

You can skip some connection settings in your code if you need.

 $cache = new RedMem();

Example of Redis connection:

 $cache->connect('Redis', array('server' => '127.0.0.1', 'port' => 6379));

Example of Memcache connection:

 $cache->connect('Memcache', array('servers' => array('127.0.0.1')));  

Usage

Write:

 $cache->write('key', 'value');

Read:

 $var = $cache->read('key');

Delete:

 $cache->delete('key');

Increment:

  $cache->write('integer1', 1);      
  $var = $cache->increment('integer1'); //returns 2
  $var = $cache->increment('integer1', 100); //returns 102

Decrement:

  $cache->write('integer1', 100);      
  $var = $cache->decrement('integer1'); //returns 99
  $var = $cache->decrement('integer1', 90); //returns 9

Read or update

Usually, when you work with cache, you write the code like this:

 $var = Cache::read('name');
 if(!$var) {
        // do something. 
        Cache::write('name', $var);
 }

Sometimes it's not good to write big if-blocks (really big blocks) for preparing data for cache. With RedMem we can write something like this.

Function for updating cache value:

 $function = function ($array) {
         return $array[0] + $array[1];
 };  

Dealing with cache:

 $result = $cache->readOrUpdate('key1', array('type' => 'closure', 'function' => $function, 'arg' => array(2, 3)));

This readOrUpdate means that we run $function if key1 is not available. Otherwise we return key1 from cache. Our code becomes more linear without if-blocks.

We have 3 ways to use readOrUpdate.

  1. Update cache record with value
 $result = $cache->readOrUpdate('key1', array('type' => 'variable', 'value' => 'this is value'));
  1. Update cache with function without args
 $result = $cache->readOrUpdate('key1', array('type' => 'closure', 'function' => $function));
  1. Update cache with function with args
 $result = $cache->readOrUpdate('key1', array('type' => 'closure', 'function' => $function, 'arg' => array(2, 3)));
Something went wrong with that request. Please try again.