Set ttl and namespace using Memcached in Zend Fram

2019-04-02 10:29发布

问题:

As far as I can figure this seems to be the way to set up Memcached and set the TTL and Namespace but they have no effect in the cache. The key is not prefixed with a namespace and the expire is infinite.

    $MemcachedOptions = new \Zend\Cache\Storage\Adapter\MemcachedOptions();
    $MemcachedResourceManager = new \Zend\Cache\Storage\Adapter\MemcachedResourceManager(1, new \Zend\Cache\Storage\Adapter\Memcached());
    $MemcachedResourceManager->addServer(1, array('localhost', 11211));
    $MemcachedOptions->setResourceManager($MemcachedResourceManager);

    $MemcachedOptions->setNamespace('FooBar_');
    $MemcachedOptions->setTtl(10);

    $cache = $MemcachedOptions->getResourceManager()->getResource(1);
    $cache->set('foobar_key','I am in cache');

Does anyone have any tips, clues? Any help would be much appreciated.

回答1:

The MemcachedResourceManager works different as you trying to use it.

You should initialize it like the following:

// init a memcached resource manager with one native memcached resource
// using resource id "1"
$MemcachedResourceManager = new \Zend\Cache\Storage\Adapter\MemcachedResourceManager();
$MemcachedResourceManager->addServer('1', array('localhost', 11211));

// init a memcached storage adapter
// using the native memcached resource of id "1"
// configure it with a ttl and a namespace
$cache = \Zend\Cache\StorageFactory::adapterFactory('memcached', array(
    'resource_manager' => $MemcachedResourceManager,
    'resource_id'      => '1',
    'namespace'        => 'FooBar_',
    'ttl'              => 10,
));

// or
$memcachedAdapterOptions = new \Zend\Cache\Storage\Adapter\MemcachedOptions(array(
    'resource_manager' => $MemcachedResourceManager,
    'resource_id'      => '1',
    'namespace'        => 'FooBar_',
    'ttl'              => 10,
));
$cache = new \Zend\Cache\Storage\Adapter\Memcached($memcachedAdapterOptions);

How does the classes work together:

The most important class is Zend\Cache\Storage\Adapter\Memcached it is a wrapper for a native instance of Memcached used in a context of Zend\Cache\StorageInterface.

This storage adapter has a number of options defined as Zend\Cache\Storage\Adapter\MemcachedOptions.

Because cache storage adapters in ZF2 are designed to handle one type of items to store you need different instances of Zend\Cache\Storage\Adapter\Memcached for different type of items. But you don't wont to use different connections to a memcached (different instance of the native Memcached class) server - this is were Zend\Cache\Storage\Adapter\MemcachedResourceManager comes to play.

The Zend\Cache\Storage\Adapter\MemcachedResourceManager handles native instances of Memcached which will be used by Zend\Cache\Storage\Adapter\Memcached.