我使用 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;
}
}
}
因此,除了到期日期之外,根本没有任何逻辑可以检查到期。
您是否知道在文件更改时使缓存无效的方法(当然是在开发环境中)?或者我必须自己实现它..?
谢谢你的帮助。