Symfony 4 自动装配无法正常工作

Symfony 4 autowiring not working properly

上下文如下:

  1. 使用 composer 安装 beantalk 包 "composer require leezy/pheanstalk-bundle"

  2. 我正在尝试在命令内部使用,但出现此错误

Cannot autowire service "App\Command\Worker\ProcessParserCommand": argument "$pheanstalk" of method "__construct()" references interface "Pheanstalk\Contract\PheanstalkInterface" but no such
service exists. You should maybe alias this interface to the existing "leezy.pheanstalk.proxy.default" service.

class ProcessParserCommand extends Command
{
    protected static $defaultName = 'app:worker:process-parser';

    /** @var PheanstalkInterface $pheanstalk */
    private $pheanstalk;

    protected function configure()
    {
        $this
            ->setDescription("Parse something")
        ;
    }



    public function __construct(PheanstalkInterface $pheanstalk)
    {
        $this->pheanstalk=$pheanstalk;

        parent::__construct();
    }
}

事实证明这是那些具有欺骗性的错误消息之一。

通常当您收到 "Interface does not exist, maybe alias SomeService" 消息时,这意味着接口需要明确定义为别名:

# config/services.yaml
Pheanstalk\Contract\PheanstalkInterface:
    alias: 'leezy.pheanstalk.proxy.default'

但在这种情况下,虽然这样做可以避免接口错误,但会产生新的 "too few constructor arguments" 错误。

查看捆绑包的文档表明您需要一些配置才能实际生成 pheanstalk 实例。 composer require 命令足够聪明,可以将包添加到 bundles.php 文件,但不会创建配置文件。所以根据文档添加配置文件:

# config/packages/leezy_pheanstalk.yaml
leezy_pheanstalk:
    pheanstalks:
       primary:
           server: beanstalkd.domain.tld
           default: true

很快。错误消失了。作为奖励,不再需要 config/services.yaml 中的别名,如果您添加了别名,则应将其删除。