TYPO3 11.5.25使用VariableFrontend缓存变量报错,求正确实现方法
TYPO3 11.5.25 正确存储变量到缓存的方法
你的代码报错是因为直接调用了抽象接口FrontendInterface的getBackend()方法——抽象方法无法直接调用,且这种手动创建缓存实例的方式不符合TYPO3的规范。以下是两种正确的实现方式:
方式一:依赖注入(推荐)
通过TYPO3的依赖注入容器注入CacheManager,再获取VariableFrontend实例,这是TYPO3推荐的规范写法:
use TYPO3\CMS\Core\Cache\CacheManager; use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend; class YourCustomClass { protected VariableFrontend $variableCache; // 构造函数注入CacheManager public function __construct(CacheManager $cacheManager) { // 获取系统预设的"variables"缓存前端 $this->variableCache = $cacheManager->getCache('variables'); } public function storeVariableToCache() { // 存储变量到缓存 $this->variableCache->set( 'exampleIdentifier', // 缓存标识 'nomebariabile', // 要存储的变量 ['tag-sede'], // 缓存标签(用于批量清理) 10000 // 过期时间(单位:秒) ); } }
方式二:通过全局工具类获取(适用于无法依赖注入的场景)
如果在临时脚本、插件的非构造方法等无法使用依赖注入的场景,可以用GeneralUtility获取CacheManager实例:
use TYPO3\CMS\Core\Cache\CacheManager; use TYPO3\CMS\Core\Utility\GeneralUtility; // 获取CacheManager实例 $cacheManager = GeneralUtility::makeInstance(CacheManager::class); // 获取VariableFrontend缓存实例 $variableCache = $cacheManager->getCache('variables'); // 执行缓存存储操作 $variableCache->set( 'exampleIdentifier', 'nomebariabile', ['tag-sede'], 10000 );
补充说明
variables是TYPO3默认配置好的缓存前端,如果你需要自定义缓存的后端类型、存储路径等,可以在config/system/additional.php或LocalConfiguration.php中添加缓存配置。- 不要手动实例化
VariableFrontend,缓存后端的配置应由TYPO3统一管理,避免出现配置不一致的问题。
内容的提问来源于stack exchange,提问作者MarioProject
相关产品推荐
相关产品推荐

