将服务注入 CLI Symfony 4 应用程序
Injecting services into a CLI Symfony 4 App
我有一个带有 CLI 脚本的 Symfony 4.2 应用程序,调用命令 - 工作正常。
但是在我的命令中,我正在尝试访问数据库(通过 Doctrine)。
文档建议我只需将一个构造函数添加到我的 Command 中,然后它就会被注入。除了,这是我在调用时构建命令的代码:
$applicant->add(new \App\Command\MyCommand());
如果我需要注入它,那很好,但是在这种情况下我如何从我的 CLI 脚本访问该服务?
请阅读文档
https://symfony.com/doc/current/console.html
Registering the Command
Symfony commands must be registered as services and tagged with the console.command tag. If you're using the default services.yaml configuration, this is already done for you, thanks to autoconfiguration.
Executing the Command
After configuring and registering the command, you can execute it in the terminal:
php bin/console app:create-user
As you might expect, this command will do nothing as you didn't write any logic yet. Add your own logic inside the execute() method.
如您所见,稍后您可以通过 bin/console 调用您的命令。
为了让命令能够访问数据库,你需要注入特定的服务,我不喜欢注入整个容器,但这里有一个例子给你
Symfony 4: doctrine in command
我有一个带有 CLI 脚本的 Symfony 4.2 应用程序,调用命令 - 工作正常。
但是在我的命令中,我正在尝试访问数据库(通过 Doctrine)。
文档建议我只需将一个构造函数添加到我的 Command 中,然后它就会被注入。除了,这是我在调用时构建命令的代码:
$applicant->add(new \App\Command\MyCommand());
如果我需要注入它,那很好,但是在这种情况下我如何从我的 CLI 脚本访问该服务?
请阅读文档 https://symfony.com/doc/current/console.html
Registering the Command Symfony commands must be registered as services and tagged with the console.command tag. If you're using the default services.yaml configuration, this is already done for you, thanks to autoconfiguration.
Executing the Command After configuring and registering the command, you can execute it in the terminal:
php bin/console app:create-user
As you might expect, this command will do nothing as you didn't write any logic yet. Add your own logic inside the execute() method.
如您所见,稍后您可以通过 bin/console 调用您的命令。 为了让命令能够访问数据库,你需要注入特定的服务,我不喜欢注入整个容器,但这里有一个例子给你 Symfony 4: doctrine in command