Symfony3:如何以正确的方式启用 PDO/Doctrine 缓存适配器?

问题描述

喂!

我正在尝试让缓存适配器在 Symfony 3.4 中运行。我在这个项目中使用了学说,所以似乎可以使用该适配器(我在 2 个容器中运行该服务,所以我需要一个缓存系统,这两个容器可以访问.....并且没有 Redis/Memcache ...所以请不要就此提出建议;)).

以下是我做的配置的相关部分:

 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:...
      ...

我还加了一个migration来添加对应的表: 使用以下查询(如 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 

当我尝试使用它时,我只会遇到缓存未命中....

示例:

$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();

我错过了什么?

感谢您的帮助:)

解决方法

我发现了如何让它发挥作用。经过一天的调试,似乎在 symfony 3.4 中使用该应用程序的服务获得了一个命名空间而不是给定的连接,因为在 symfony 的 DI 组件中它没有实现使用 PDOAdapter。

我现在所做的是将 PDOAdapter 服务直接注入到需要的服务中:

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' ]

然后当然是注入它(我之前也做过但没有提到它):

use Symfony\Component\Cache\Adapter\AdapterInterface;

class HeavyCacheUser
  private $cache;
  public function __construct(AdapterInterface $cacheAdapter){
    $this->cache = $cache;
  }

愿它帮助其他受苦的人^^