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

解决TYPO3 11中createQuery()调用空对象的错误问题

TYPO3 11下解决ViewHelper中Call to a member function createQuery() on null错误的方案

这个错误的核心原因是TYPO3 11对依赖注入(DI)的机制做了严格升级,原TYPO3 10中依赖属性自动注入的方式不再可靠,导致$categoryRepository没有被正确实例化,最终返回null。以下是具体解决步骤:

1. 改用构造函数注入(推荐方案)

构造函数注入是Symfony DI体系的最佳实践,在TYPO3 11+中兼容性更强,也更易于调试。

修改ViewHelper代码如下:

use TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class FileCategoriesViewHelper extends AbstractViewHelper
{
    protected CategoryRepository $categoryRepository;

    // 通过构造函数注入CategoryRepository
    public function __construct(CategoryRepository $categoryRepository)
    {
        $this->categoryRepository = $categoryRepository;
    }

    public function render()
    {
        // 此时$categoryRepository已被正确实例化
        $query = $this->categoryRepository->createQuery();
        // 后续业务逻辑...
    }
}

2. 备选:使用属性注入(PHP 8+注解方式)

如果偏好属性注入,需添加TYPO3官方的#[Inject]注解,替代原TYPO3 10中可能依赖的注释注入:

use TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository;
use TYPO3\CMS\Extbase\Annotation\Inject;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class FileCategoriesViewHelper extends AbstractViewHelper
{
    // 添加#[Inject]注解触发依赖注入
    #[Inject]
    protected CategoryRepository $categoryRepository;

    public function render()
    {
        $query = $this->categoryRepository->createQuery();
        // 后续业务逻辑...
    }
}

3. 关键注意事项

  • 移除手动给$categoryRepository赋值的代码(比如赋值为空字符串),完全由DI容器负责实例化。
  • 确保正确引入CategoryRepository的命名空间:\TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository,不要使用错误的命名空间导致注入失败。
  • 检查扩展的Configuration/Services.yaml配置,确保开启了自动注入:
    services:
      _defaults:
        autowire: true
        autoconfigure: true
        public: false
    
      # 若ViewHelper需要被外部访问,可手动声明(多数场景下自动扫描即可)
      Vendor\YourExtension\ViewHelpers\FileCategoriesViewHelper:
        public: true
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:27:21