ZF2在运行时将参数传递给工厂

时间:2016-03-27 09:40:05

标签: zend-framework zend-framework2

在ZF2中,我有一个多工具箱的工厂(简化)

class MultiCheckboxFactory
{
    public function __invoke(FormElementManager $formElementManager)
    {
        $multiCheck = new MultiCheckbox();

        $serviceManager = $formElementManager->getServiceLocator();
        $mapper = $serviceManager->get('Path\To\The\Mapper\SomeMapper');
        $resultFromQuery = $mapper->findText('text');

        // further setting up of the multicheckbox based on $resultFromQuery

        return $multiCheck;
    }
}

我希望multiheckbox根据来自mapper $resultFromQuery方法的findText()呈现不同的内容。

我想过将变量传递给__invoke(FormElementManager $formElementManager, $someText)。但问题是,当我从服务管理器中调用multiheckbox时,如下所示:

$element = $formElementManager->get('Path\To\Factory\Alias\Multicheckbox');

我不知道如何传递额外的变量。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

查看MutableCreationOptionsInterface,这样您的工厂就可以接收通过serviceManager get()方法传递的运行时选项。

use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\MutableCreationOptionsTrait;

class MultiCheckboxFactory implements MutableCreationOptionsInterface
{
    use MutableCreationOptionsTrait;

    public function __invoke(FormElementManager $formElementManager)
    {
        $options = $this->getCreationOptions();

        var_dump($options);

        $multiCheck = new MultiCheckbox();

        ....
    }
}

现在你可以传递选项:

$element = $formElementManager->get('Path\To\Factory\Alias\Multicheckbox', ['foo' => 'bar']);

答案 1 :(得分:2)

更新:MutableCreationOptionsTrait在ZF3中不再可用:https://docs.zendframework.com/zend-servicemanager/migration/#miscellaneous-interfaces-traits-and-classes

现在最简单的方法似乎是

$element = $formElementManager->build('Path\To\Factory\Alias\Multicheckbox', ['foo' => 'bar']);

虽然这样每次都会给你一个离散的(不是共享的)实例。