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

时间:2018-09-11 20:45:36

标签: dependency-injection zend-framework2 service-locator

是否可以创建服务的新实例并添加构造函数参数?我对依赖注入有些陌生,我发现只能将服务添加为构造函数参数,而不能通过工厂添加运行时变量。

我的代码与此类似:

Class MyService
{
    private $name;
    private $active;

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

$myService = $this->getServiceLocator()->get('MyService')

2 个答案:

答案 0 :(得分: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',
]);

容易做馅饼。 ;)

答案 1 :(得分:0)

假设您的服务存在:

Class MyService
{
    private $name;
    private $active;

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

如果不是->get(),则可以->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);