• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

根据命令参数服务动态注入 Symfony 命令.

用户头像
it1352
帮助1

问题说明

我有一个 Symfony 命令,它接受一个参数作为所需特定服务的定位器(基于该参数).

I have a Symfony command that takes an argument which serves as a locator to a specific service required (based on that argument).

即.

bin/console some:command service-locator-id

使用 Symfony 2.8,您可以简单地从容器中获取服务

with Symfony 2.8 you can simply fetch the service from the container

$service = $this->container->get($input->getArgument('service-locator-id'));

然而,在 Symfony 3.4 中,容器已被弃用,我们应该使用依赖注入.

With Symfony 3.4 however, the container is deprecated and we should be using Dependency Injection.

如何根据传递给 Command 的参数注入我需要的服务?

How do I inject the service that I require based on the argument being passed into the Command ?

正确答案

#1

好的,我终于能够使用服务定位器文档解决这个问题了.

Ok, I was finally able to figure this out using the service locator documentation.

https://symfony.com/doc/3.4/service_container/service_subscribers_locators.html

基本上,

class MyCommand extends ContainerAwareCommand implements ServiceSubscriberInterface
{

    private $locator;

    private $serviceId;

    public static function getSubscribedServices()
    {
        return [
            'service-locator-id-one' => ServiceClassOne::class,
            'service-locator-id-two' => ServiceClassTwo::class,
        ];
    }

    /**
     * @required
     * @param ContainerInterface $locator
     */
    public function setLocator(ContainerInterface $locator)
    {
        $this->locator = $locator;
    }

    protected function configure()
    {
        $this
        ->setName('some:command')
        ->addArgument('service-locator-id', InputArgument::REQUIRED, 'Service Identifier');
    }

    /**
     * 
     * @return void|MyServiceInterface
     */
    private function getService()
    {
        if ($this->locator->has($this->serviceId)) {
            return $this->locator->get($this->serviceId);
        }
    }
}

完美运行.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanheceakk
系列文章
更多 icon
同类精品
更多 icon
继续加载