问题描述
在我的 Symfony 5 应用程序中,我想为不同的任务使用不同的缓存,当然还有不同的环境。
例如我的配置如下:
framework:
cache:
pools:
cache.auth:
adapter: cache.adapter.redis
provider: app.my_custom_redis_provider
cache.sap:
adapter: cache.adapter.redis
provider: app.my_custom_redis_provider
services:
app.my_custom_redis_provider:
arguments:
- '%env(REdis_URL)%'
-
retry_interval: 2
timeout: '%env(REdis_TIMEOUT)%'
class: Redis
factory:
- Symfony\Component\Cache\Adapter\RedisAdapter
- createConnection
我在我的类中使用依赖注入。那么我将如何定义特定类使用这两个缓存池中的哪一个?
目前我的缓存是这样的:
class SapListService implements ListServiceInterface
{
use LoggerTrait;
private CountryServiceInterface $countryService;
private CurrencyServiceInterface $currencyService;
public function __construct(
SapClientFactoryInterface $sapClient,CacheItemPoolInterface $cache,ParameterBagInterface $params
) {
$sapUser = $params->get('sap_user');
$sapPw = $params->get('sap_pw');
$urlStruktur = $params->get('sap_struktur');
$this->countryService = $sapClient->getCountryService($sapUser,$sapPw,$urlStruktur,$cache);
$this->currencyService = $sapClient->getCurrencyService($sapUser,$cache);
}
如何配置我的 SapListService
以使用 cache.sap 池?
解决方法
这在 docs 中有解释。
每个自定义池成为一个服务,其服务 ID 是池的名称(例如 custom_thing.cache)。还使用其名称的驼峰式版本为每个池创建了一个自动装配别名 - 例如custom_thing.cache 可以通过命名参数 $customThingCache 并使用 Symfony\Contracts\Cache\CacheInterface 或 Psr\Cache\CacheItemPoolInterface 进行类型提示来自动注入:
所以在你的情况下,你可以输入提示:
Psr\Cache\CacheItemPoolInterface $cacheSap