Aistina Aistina - 3 months ago 39
PHP Question

How to use Memcached in Doctrine2 / ZF2?

I have set up my code / directories / configuration as outlined in this article: http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/

So my config file looks something like:

<?php
namespace Game;

return array(

// <snip>

// Doctrine config
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
)
)
)
),
);


Now, what do I need to set/change to make Doctrine use Memcached as its caching backend? I have searched a lot on Google, but other than in this question, where it says they got it working (but not how), I have not been able to find anything.

Answer

I had some trouble to get it working and I only have a temporary workaround as I needed to modify the Doctrine ORM Module itself.

First, set the cache to memcache: 'cache' => 'array', to 'cache' => 'memcache', in your config above.

Then, define a service factory to create the memcache instance. You can do this in a module class:

NOTE: This example bases on memcache, not memcacheD. But it should be the same for memcached.

function getServiceConfig()
{
    return array(
        'factories' => array(
            'memcache' => function(ServiceManager $sm) {
                $memcache = new \Memcache(); // .. do some configuration and connect
                return $memcache;
            } 
        )
    );
}

The last step is to modify the Doctrine ORM Module. Otherwise, it won't create the instance and throws an error.

In DoctrineModule/Service/CacheFactory.php l61 :

$cache->setMemcache($options->getInstance());

Becomes:

$cache->setMemcache($sl->get($options->getInstance()));

(In your case, do this for line 64.) Or find another way to inject a memcached instance into $options. Be aware that this should only be a workaround and be fixed as soon as possible. Otherwise, you'll have trouble updating the module.

Hope this helps.

Comments