ZF2:在服务构造函数中注入变量

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

有没有办法创建服务的新实例并添加构造函数参数?我对依赖注入有点新,我发现我只能通过工厂添加服务作为构造函数参数而不是运行时变量。

我看到的代码与此类似:

Class MyService
{
    private $name;
    private $active;

    public function __construct($name,$active)
    {
        $this->name = $name;
        $this->active = $active;    
    }
}

$myService = $this->getServiceLocator()->get('MyService')
dependency-injection zend-framework2 service-locator
2个回答
0
投票

是的,有一种方法可以在您的工厂中使用MutableCreationOptionsTrait特性。

class YourServiceFactory implements FactoryInterface, MutableCreationOptionsInterface
{
    use MutableCreationOptionsTrait;

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        if (isset($this->creationOptions['name'])) {
            // do something with the name option
        }

        if (isset($this->creationOptions['active'])) {
            // do something with the active option
        }

        $yourService = new YourService(
            $this->creationOptions['active'], 
            $this->creationOptions['name']
        );

        return $yourService;
    }
}

上面显示的代码实现了创建选项的特征。有了这个特性,您可以在工厂中处理一系列选项。按以下代码调用您的服务。

$yourService = $this->getServiceLocator()->get(YourService::class, [
    'active' => true,
    'name' => 'Marcel',
]);

非常简单。 ;)


0
投票

假设您的服务存在:

Class MyService
{
    private $name;
    private $active;

    public function __construct($name,$active)
    {
        $this->name = $name;
        $this->active = $active;    
    }
}

如果不是->get()'ing它,你可以->build()它:)

class SomeFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return $container->build(MyService::class, ['name' => "Foo", 'active' => true]);
        // Line below works as well, using a variable requested name, handy for an AbstractFactory of some kind (e.g. one that creates different adapters in the same way with same params)            
        // return $container->build($requestedName, ['name' => "Foo", 'active' => true]); 
    }
}

看看ServiceManager build() function


注意:不确定,因为它存在时,它适用于更高版本的ZF2和所有ZF3。


注2:get()build()都叫function doCreate()。功能声明:

private function doCreate($resolvedName, array $options = null)

get()$object = $this->doCreate($name);

build()return $this->doCreate($name, $options);

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