Symfony 4自定义容器感知命令错误

问题描述 投票:1回答:2

我正在尝试在Symfony 4项目中创建自定义命令

class AppOauthClientCreateCommand extends ContainerAwareCommand
{

   protected function configure()
   {
     $this
        ->setName('app:oauth-client:create')
        ->setDescription('Create a new OAuth client');
   }

   protected function execute(InputInterface $input, OutputInterface $output)
   {
    $clientManager = $this->getContainer()->get('fos_oauth_server.client_manager.default');
    $client = $clientManager->createClient();
    $client->setAllowedGrantTypes(array(OAuth2::GRANT_TYPE_USER_CREDENTIALS));
    $clientManager->updateClient($client);

    $output->writeln(sprintf('client_id=%s_%s', $client->getId(), $client->getRandomId()));
    $output->writeln(sprintf('client_secret=%s', $client->getSecret()));
   }
}

我尝试运行此命令时收到以下错误

编译容器时,已删除或内联“fos_oauth_server.client_manager.default”服务或别名。你也应该 使其公开,或直接停止使用容器并改为使用依赖注入。

如何使供应商服务公开或我在命令配置中遗漏了什么?

php symfony symfony4
2个回答
3
投票

问题是,自Symfony 4以来,默认情况下所有服务都是私有的。实际上,使用服务容器的get方法无法获得私有服务。

您应该避免在服务中注入整个容器(或通过扩展qazxsw poi来命令)。相反,您应该只注入所需的服务:

ContainerAwareCommand

如果class AppOauthClientCreateCommand { /** * @var ClientManagerInterface */ private $clientManager; public function __construct(ClientManagerInterface $clientManager) { $this->clientManager = $clientManager; } protected function configure() { ... } protected function execute(InputInterface $input, OutputInterface $output) { $client = $this->clientManager->createClient(); ... } } 未自动装配,那么您必须在services.yaml中配置具有适当依赖关系的ClientManagerInterface。就像是:

AppOauthClientCreateCommand

希望这可以帮助。


1
投票

您需要检查services: App\Command\AppOauthClientCreateCommand: arguments: $clientManager: "@fos_oauth_server.client_manager.default" 命令的输出以获取相应的接口,以便在构造函数中使用“fos_oauth_server.client_manager。*”。应该已经设置了自动装配,以允许容器识别并从那里插入它。

这将需要FosOauthServer支持SF4 - 并且在构造函数中记得也要调用./bin/console debug:autowiring来正确设置命令。你可以这样做,仍然使用ContainerAwareCommand从容器中parent::__construct();其他东西 - 但你可能会随着时间的推移而远离它。

© www.soinside.com 2019 - 2024. All rights reserved.