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

TYPO3扩展中ConnectionPool实例化问题:Symfony命令依赖注入报错

问题分析与解决方案

你的代码存在问题,并非手册内容有误。

报错原因

你重写了命令类的构造函数,但未调用父类Command的构造方法。Symfony的Command父类本身需要接收命令名称参数(可选,但需提供默认值或显式传递),你只定义了自己的依赖参数,导致实例化时无法满足父类构造函数的参数要求,从而抛出"参数不足"的错误。

正确的代码写法

修改构造函数,调用父类构造方法并处理命令名称参数:

namespace MyVendor\MyExtension\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\CMS\Core\Database\ConnectionPool;

class MyClassCommand extends Command {
    // 方式1:给命令名称参数设默认值
    public function __construct(
        private readonly ConnectionPool $connectionPool,
        string $name = null
    ) {
        parent::__construct($name);
    }

    // 方式2:显式指定命令名称
    // public function __construct(private readonly ConnectionPool $connectionPool) {
    //     parent::__construct('my:custom:command');
    // }

    // 执行命令的核心逻辑
    protected function execute(InputInterface $input, OutputInterface $output): int {
        // 通过依赖注入的connectionPool获取QueryBuilder
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('your_table');
        // ... 后续业务逻辑
        return Command::SUCCESS;
    }
}

额外注意事项

  1. 命令注册:确保你的命令类已正确注册到DI容器,可通过两种方式实现:

    • 在Configuration/Services.yaml中添加标签:
      services:
        MyVendor\MyExtension\Command\MyClassCommand:
          tags:
            - name: console.command
              command: 'my:custom:command'
      
    • 或者在命令类上使用#[AsCommand]注解(TYPO3 12支持):
      use Symfony\Component\Console\Attribute\AsCommand;
      
      #[AsCommand(
          name: 'my:custom:command',
          description: '自定义命令的描述信息'
      )]
      class MyClassCommand extends Command {
          // ...
      }
      
  2. 关于手册的说明:手册中不建议使用GeneralUtility::makeInstance()是正确的,因为直接实例化ConnectionPool会丢失TYPO3运行时的上下文配置(如权限检查、数据库连接上下文),而通过DI注入的方式能保证这些依赖被正确初始化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:46:23