【发布时间】:2021-10-15 16:19:35
【问题描述】:
我一直在使用 symfony/console 来制作命令并像这样注册它们,一切正常:
bin/控制台:
#!/usr/bin/env php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Commands\LocalitiesCommand;
use Symfony\Component\Console\Application;
$app = new Application();
$app->add(new LocalitiesCommand(new LocalitiesGenerator()));
$app->run();
src/Commands/LocalitiesCommand.php:
<?php
declare(strict_types=1);
namespace App\Commands;
use App\LocalitiesGenerator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class LocalitiesCommand extends Command
{
protected static $defaultName = 'app:generate-localities';
public function __construct(private LocalitiesGenerator $localitiesGenerator)
{
parent::__construct();
}
protected function configure(): void
{
$this
->setDescription('Generate localities.json file')
->setHelp('No arguments needed.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->localitiesGenerator->generateJsonLocalities();
$output->writeln("File localities.json generated!");
return Command::SUCCESS;
}
}
现在我想用 symfony/dependency-injection 自动注入服务,我正在阅读文档并做了一些更改:
新的bin/console:
#!/usr/bin/env php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Commands\LocalitiesCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/src/config'));
$loader->load('services.yaml');
$container->compile();
$app = new Application();
$app->add(new LocalitiesCommand());
$app->run();
config/services.yaml:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
但是当我实例化我的命令时,仍然要求我在构造函数中添加我的服务。为什么它不起作用?
【问题讨论】:
-
你在用 composer 吗?
-
@RudyDavid 是的,我正在使用作曲家
-
@yivi 可能我看过一些教程,而且 symfony 允许将服务注入到命令中,你可以在这里查看:symfony.com/doc/current/…
-
@yivi Aah 现在我明白你的意思对不起,我能读到什么来实现我想要的或你知道的任何文档?
-
改变 $app->add(new LocalitiesCommand());到 $app->add($container->get(LocalitiesCommand::class); 并公开你的服务可能会成功。但老实说,一旦你开始在这些事情中使用容器,然后只使用 symfony/skeleton app 更有意义。我还假设您只显示了 services.yaml 文件的一部分。您显然需要实际扫描目录或至少将您的命令添加为服务。
标签: php symfony dependency-injection symfony-console