如何将Symfony 4自带的缓存实例注入到服务/控制器中?
嘿,我来帮你搞定Symfony 4自带缓存实例的使用问题!你完全不需要自己手动构建缓存路径,Symfony已经为我们封装好了开箱即用的缓存服务,不管是控制器还是自定义服务,都能轻松注入使用。
一、在控制器中使用自带缓存
如果你的控制器继承了AbstractController,最推荐的方式是通过依赖注入直接获取缓存服务,这符合Symfony的最佳实践:
namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\HttpFoundation\Response; class DemoController extends AbstractController { public function index(AdapterInterface $cache): Response { // 获取指定key的缓存项 $cacheItem = $cache->getItem('demo_cache_key'); // 检查缓存是否命中 if (!$cacheItem->isHit()) { // 缓存未命中时,生成需要缓存的数据 $cachedData = "这是要缓存的内容,比如数据库查询结果、复杂计算值"; // 设置缓存内容,并指定过期时间(这里是1小时) $cacheItem->set($cachedData)->expiresAfter(3600); // 保存缓存 $cache->save($cacheItem); } return new Response('缓存内容:' . $cacheItem->get()); } }
如果你需要指定使用配置里的app缓存池,也可以直接注入Symfony\Contracts\Cache\CacheInterface,它默认对应cache.app服务。
二、在自定义服务中注入缓存
Symfony 4默认支持自动注入,所以你的自定义服务可以直接在构造函数中声明缓存依赖:
namespace App\Service; use Symfony\Component\Cache\Adapter\AdapterInterface; class DemoService { private $cache; // 自动注入缓存服务 public function __construct(AdapterInterface $cache) { $this->cache = $cache; } public function getCachedData() { $cacheItem = $this->cache->getItem('service_demo_key'); if (!$cacheItem->isHit()) { $data = "服务生成的需要缓存的数据"; $cacheItem->set($data)->expiresAfter(1800); // 30分钟过期 $this->cache->save($cacheItem); } return $cacheItem->get(); } }
如果你的服务需要特定的缓存池(比如后续配置了Redis或APCu缓存),可以直接注入对应的服务,比如cache.app对应的类是Symfony\Component\Cache\Adapter\FilesystemAdapter,直接在构造函数中声明即可。
为什么你的临时方案可以替换?
Symfony自带的缓存服务会自动根据当前环境(dev/prod/test)管理缓存路径,缓存文件默认存在var/cache/{环境名}/pools/目录下,完全不需要你手动判断环境并构建路径,既省心又符合框架的规范。
你的framework.yaml里的缓存配置已经是默认的文件系统缓存,不需要额外修改就能正常使用上面的方法。
内容的提问来源于stack exchange,提问作者k00ni
相关产品推荐
相关产品推荐

