0
我使用Symfony 3.1的cache component来存储我的实体的一些自定义元数据。只要在与这些元数据相关联的任何文件中进行更改,我都想使其无效。Symfony 3.1缓存组件中的缓存失效
我没有找到一种方法来告诉Symfony或缓存组件,特别是监视一组特定文件的更改,我错过了什么?
下面我用它来创建我的缓存条目池代码:
<?php
class MetadataCacheFactory implements MetadataCacheFactoryInterface
{
const CACHE_NAMESPACE = 'my_namespace';
/** @var string */
protected $cacheDir;
public function __construct(KernelInterface $kernel)
{
$this->cacheDir = $kernel->getCacheDir();
}
/**
* {@inheritdoc}
*/
public function create(): CacheItemPoolInterface
{
return AbstractAdapter::createSystemCache(self::CACHE_NAMESPACE, 0, null, $this->cacheDir);
}
}
和代码使用它:
<?php
class ExampleMetadataFactory implements MetadataFactoryInterface
{
const CACHE_KEY = 'example_metadata';
[...]
/** @var ExampleMetadata */
protected $metadata;
public function __construct(MetadataCacheFactoryInterface $cacheFactory)
{
$this->cache = $cacheFactory->create();
$this->metadata = null;
}
/**
* {@inheritdoc}
*/
public function create(): ExampleMetadata
{
if ($this->metadata !== null) {
return $this->metadata;
}
try {
$cacheItem = $this->cache->getItem(md5(self::CACHE_KEY));
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
} catch (CacheException $e) {
// Ignore
}
$this->metadata = $this->createMetadata();
if (!isset($cacheItem)) {
return $this->metadata;
}
$cacheItem->set($this->metadata);
$this->cache->save($cacheItem);
return $this->metadata;
}
}
当我看到在运行时代码中,AbstractAdapter
选择放弃我PhpFilesAdapter
(公平的开发我猜)。
但当我看这个适配器的代码,我发现这一点:
<?php
protected function doFetch(array $ids) {
[...]
foreach ($ids as $id) {
try {
$file = $this->getFile($id);
list($expiresAt, $values[$id]) = include $file;
if ($now >= $expiresAt) {
unset($values[$id]);
}
} catch (\Exception $e) {
continue;
}
}
}
所以没有逻辑可言检查期满除了到期日。
你知道一种方法来使文件更改时的缓存无效(当然在开发环境中)吗?或者让我自己来实现它..?
感谢您的帮助。