You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Twig应用扩展添加缓存?我的缓存实现为何未生效?

问题:Twig自定义函数缓存未生效

我想缓存Twig模板中调用的函数结果,模板代码如下:

<h3>{{ cached_date() }}</h3>

我按照Symfony官方Cache Contracts教程实现了最小可行版本,代码如下:

<?php
// src/Twig/AppExtension.php
namespace App\Twig;

use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{

    public function getFunctions()
    {
        return [new TwigFunction('cached_date', [$this, 'get_date']),];
    }

    public function get_date() {
        $cache = new FilesystemAdapter();
        $value = $cache->get('cached_date', function (ItemInterface $item) {
            $item->expiresAfter(3600);
          
            $date = date("Y-m-d H:i:s");

            return $date;
      });

      return $value;

    }
}

我确认函数能正常执行(直接返回非缓存值时可渲染到模板),也已经执行composer require symfony/cache安装了依赖,但缓存始终不生效,请问还缺什么配置或步骤?


解决方案
  • 不要每次调用都新建缓存适配器
    当前代码在每次执行get_date()时都会创建新的FilesystemAdapter实例,导致缓存上下文不共享,无法读取之前存储的缓存项。正确做法是通过依赖注入注入缓存服务,而非在方法内实例化。

修改后的AppExtension代码:

<?php
// src/Twig/AppExtension.php
namespace App\Twig;

use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\CacheInterface;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function __construct(
        private CacheInterface $cache
    ) {}

    public function getFunctions()
    {
        return [new TwigFunction('cached_date', [$this, 'get_date']),];
    }

    public function get_date() {
        $value = $this->cache->get('cached_date', function (ItemInterface $item) {
            $item->expiresAfter(3600);
          
            $date = date("Y-m-d H:i:s");

            return $date;
        });

        return $value;
    }
}
  • 确认缓存配置(可选)
    Symfony默认会自动为CacheInterface注入默认缓存池。如果需要自定义缓存规则,可在config/packages/cache.yaml中配置:
framework:
    cache:
        app: cache.adapter.filesystem
        # 可替换为其他适配器,如Redis、Memcached等
  • 清理无效缓存
    之前多次创建不同适配器实例可能生成了无效缓存文件,执行以下命令清空缓存:
php bin/console cache:clear

内容的提问来源于stack exchange,提问作者Terence Eden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:33:19