根据环境自动装配symfony CacheInterface [英] Autowire symfony CacheInterface depending on environment
问题描述
我正在尝试在我的环境中使用其他缓存系统.例如,我想拥有 dev 的 Filesystem
和 pro 的 memcached
.
I am trying to use different cache system on my environments. I would like to have, for example, Filesystem
for dev and memcached
for prod.
我正在使用 symfony 3.3.10 .
要实现此目的,我想按以下步骤自动连接 CacheInterface :
To achieve this, I would like to autowire the CacheInterface as follow:
use Psr\SimpleCache\CacheInterface;
class Api {
public function __construct(CacheInterface $cache)
{
$this->cache = $cache;
}
}
这是我的配置文件:
config_dev.yml :
framework:
cache:
app: cache.adapter.filesystem
config_prod.yml :
framework:
cache:
app: cache.adapter.memcached
...
这是我得到的错误:
将 FilesystemCache 声明为服务时,错误消失:
The error disappears when the FilesystemCache is declared as a service:
services:
Symfony\Component\Cache\Simple\FilesystemCache: ~
但是现在我不能为 test 环境提供另一个缓存系统,例如 NullCache .实际上,我只需要声明一个从 CacheInterface 继承的服务.这是不可能的,因为 config_test 也在使用 config_dev .
But now I cannot have another cache system for the test environment like NullCache. In fact, I have to declare only one service inheriting from CacheInterface. It is not possible as config_test is using config_dev too.
这是 services.yml 的开始,如果有帮助的话:
This is the beginning of services.yml if it can help:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
关于如何根据环境自动连接不同的缓存系统的任何想法吗?
这是有效的配置:
use Psr\Cache\CacheItemPoolInterface;
class MyApi
{
/**
* @var CacheItemPoolInterface
*/
private $cache;
public function __construct(CacheItemPoolInterface $cache)
{
$this->cache = $cache;
}
}
config.yml :
framework:
# ...
cache:
pools:
app.cache.api:
default_lifetime: 3600
services.yml :
# ...
Psr\Cache\CacheItemPoolInterface:
alias: 'app.cache.api'
推荐答案
即使工厂模式是解决此类问题的一个不错的选择,但对于Symfony缓存系统,通常不需要这样做.改用 CacheItemPoolInterface
提示:
Even though factory pattern is a good option to solve this kind of problematic, normally you don't need to do that for Symfony cache system. Typehints CacheItemPoolInterface
instead:
use Psr\Cache\CacheItemPoolInterface;
public function __construct(CacheItemPoolInterface $cache)
它会根据活动环境自动注入当前的 cache.app
服务,因此Symfony会为您完成这项工作!
It automatically inject the current cache.app
service depending on the active environment, so Symfony does the job for you!
只需确保为每个环境配置文件配置 framework.cache.app
:
Just make sure to configure the framework.cache.app
for each environment config file:
# app/config/config_test.yml
imports:
- { resource: config_dev.yml }
framework:
#...
cache:
app: cache.adapter.null
services:
cache.adapter.null:
class: Symfony\Component\Cache\Adapter\NullAdapter
arguments: [~] # small trick to avoid arguments errors on compile-time.
由于 cache.adapter.null
服务默认情况下不可用,因此您可能需要手动定义它.
As cache.adapter.null
service isn't available by default, you might need define it manually.
这篇关于根据环境自动装配symfony CacheInterface的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!