2

I have an application that uses php with Yii2 as its REST API backend.
I code on a machine running Windows 8 64bit and WAMP 2.5 with a local instance of memcached and test on an Amazon EC2 instance running ubuntu that uses Amazon ElastiCache and running apache2.

I found that using the built-in Yii2 cache component does not allow me to set or add objects to cache with an expiration duration on either installation BUT that if I use the PHP extension directly it works like a charm.

Code example:

$cacheObject = Yii::$app->cache;

$cacheObject->add('testKey','testValue',10);

if($cacheObject->add('testKey','testValue',10))
{
    return 'Something is wrong with Yii2 cache component!';
}
else
{
    return 'Timed caching with Yii2 works!';
}
// Above code never enters else clause.


$memcachedObject = new Memcached();
$memcachedObject->addServer(CACHE_ENDPOINT,CACHE_PORT);

$memcachedObject->add('testKey2','testValue2',10);

if($memcachedObject->add('testKey2','testValue2',10))
{
    return 'Something is wrong with memcached extension';
}
else
{
    return 'Timed caching with Memcached extension works!';
}
// This code always enters else clause.

I doubt there's something I have to do to enable timed caching in Yii2.

For reference, I used the instructions from the answer to this question in order to install and run my local memcached instance - How to enable memcache in WAMP but seeing as it also happens on my EC2 instance I doubt there's a problem with my installation.

Any ideas on why this does not work?

Community
  • 1
  • 1
prismus
  • 91
  • 1
  • 9

1 Answers1

0

As you know PHP implements memcached (the server) integration with 2 different libraries:

Yii2 instead expose only one interface using useMemcached attribute in MemCache class.

See the code from MemCache class:

protected function addValue($key, $value, $duration)
{
    $expire = $duration > 0 ? $duration + time() : 0;
    return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
}

I think there's a mismatch between your php-libs of memcache/memcached (see phpinfo() ) and your Yii2 config (see useMemcached attribute - default is false).

Ivan Buttinoni
  • 4,110
  • 1
  • 24
  • 44
  • I've already checked that and there's no mismatch. I'm thinking it might be a clock problem, seeing as Yii2 always converts the duration to unix time, but I'm unsure about it because I wouldn't expect it to happen on a local instance of memcached as the memcached instance and the app server (apache) are on the same machine and thus should share the same clock. – prismus Jul 12 '15 at 08:01