Search code examples
phpsymfonycachingpdosymfony-3.4

Symfony3: How to enable PDO/Doctrine cache adapter, the right way?


Oi!

I'm trying to get the cache adapter running in Symfony 3.4. I use doctrine in this project so it seems it's ok to use that adapter (I have this service running in 2 containers, so I need a caching system, where these two containers have access to.....and there's no Redis/Memcache...so please no advice on this ;) ).

Here are the relevant parts of the configuration I made:

 services:
      cache.adapter.pdo:
        class: Symfony\Component\Cache\Adapter\PdoAdapter
        arguments: [ '@doctrine.dbal.default_connection' ]
      blahfu.using.cache:
        class: App\HeavyCacheUser
        arguments: [ '@app.cache' ]
    

framework:
  cache:
    app: cache.adapter.pdo
    
doctrine:
  dbal:
    default_connection: default
    connections:
      default:...
      ...

I also added an migration to add the corresponding table: with the following query (as seen in src/Symfony/Component/Cache/Traits/PdoTrait.php):

CREATE TABLE cache_items (
  item_id VARBINARY(255) NOT NULL PRIMARY KEY, 
  item_data MEDIUMBLOB NOT NULL, 
  item_lifetime INTEGER UNSIGNED, 
  item_time INTEGER UNSIGNED NOT NULL
) COLLATE utf8_bin, ENGINE = InnoDB 

When I try to use it, I only get cache misses....

Example:

$cacheKey = 'blahfu.bar';

$item = $this->cache->getItem($cacheKey);

if (!$item->isHit()) {
  // Do $stuff
  
  $item->set($stuff)->expiresAfter(900);
  $this->cache->save($item);
  Logger::info('Cache miss');
} else {
  Logger::info('Cache hit');
}

return $item->get();

What am I missing?

Thanks for helping :)


Solution

  • I found out how to get that working. After a day of debugging, it seems that in symfony 3.4 the service which is using the app get a namespace instead of the given connection, because in the DI component of symfony it's not implemented to use the PDOAdapter.

    What I did now, was injecting the PDOAdapter service directly into the service in need:

    services:
          cache.adapter.pdo:
            class: Symfony\Component\Cache\Adapter\PdoAdapter
            arguments: [ '@doctrine.dbal.default_connection' ]
          blahfu.using.cache:
            class: App\HeavyCacheUser
            arguments: [ '@cache.adapter.pdo' ]
    

    And then of course injecting it (which I also did before but haven't mentioned it):

    use Symfony\Component\Cache\Adapter\AdapterInterface;
    
    class HeavyCacheUser
      private $cache;
      public function __construct(AdapterInterface $cacheAdapter){
        $this->cache = $cache;
      }
    

    May it helps someone else who suffers ^^