How to Share Memcache Entries Between Yii and Custom PHP Application

How to Share Memcache Entries Between Yii and Custom PHP Application

Do you have a php application that saves cache entry and you want Yii to have acccess to it? Or vice versa?

Yii Settings (main.php)

'cache' => array (
    'class' => 'CMemCache',
    'servers'=>array(
        array(
            'host'=>'localhost',
            'port'=>11211,
        ),
    ),
    'keyPrefix' => 'MYAPP_',
    'hashKey' => false,
),


Custom PHP Application

function get($keyName){
    // should be the same with your Yii cache settings
    $keyPrefix = 'MYAPP_';
    $hashKey = false;

    $cacheKey = $hashKey ? md5($keyPrefix.$keyName) : $keyPrefix.$keyName;

    $memcache = new Memcache;

    // should be the same with your Yii cache settings
    $memcache->addServer('localhost', 11211);

    $data = $memcache->get($cacheKey);

    $value = unserialize($data);

    return $value[0];
}


function set($keyName, $value, $expiry){
    // should be the same with your Yii cache settings
    $keyPrefix = 'MYAPP_';
    $hashKey = false;

    $cacheKey = $hashKey ? md5($keyPrefix.$keyName) : $keyPrefix.$keyName;

    $data = serialize(array($value, null));

    $memcache = new Memcache;

    // should be the same with your Yii cache settings
    $memcache->addServer('localhost', 11211);

    return $memcache->set($cacheKey, $data, MEMCACHE_COMPRESSED, $expiry);
}