在ZF2中的fieldset中获取objectManager / serviceLocator

时间:2013-02-26 10:51:47

标签: zend-framework2 service-locator

为了让我的对象管理器在我的fieldset的init()函数中,我跟着docs 起初我发现我必须改变

public function setServiceLocator(ServiceLocator $sl)

public function setServiceLocator(ServiceLocatorInterface $sl)

否则我收到错误:

setServiceLocator() must be compatible with that of Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()

调用$this->getServiceLocator()时,我得到一个FormManager实例。 另外,调用$this->getServiceLocator()->getServiceLocator()会返回NULL

由于我还是DI的新手,我想知道我是否错过了注射的地方?

测试我从

切换
$form = new MyForm();

$formManager = $this->serviceLocator->get('FormElementManager');
$form        = $formManager->get('Application\Form\MyForm');

从那以后我收到了这个错误:

exception 'Zend\Di\Exception\RuntimeException' with message 'Invalid instantiator of type "NULL" for "Zend\ServiceManager\ServiceLocatorInterface".'
An abstract factory could not create an instance of applicationformmyform(alias: Application\Form\MyForm).

不建议使用ServiceLocator Awareness读取其他一些线程。使用FormElementProviderInterface替代方案吗?

我之前在我的类中使用过ServiceLocatorAwareInterface:

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MyClass implements ServiceLocatorAwareInterface
{
    protected $services;

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->services = $serviceLocator;
    }

    public function getServiceLocator()
    {
        return $this->services;
    }

并简单地在我的c

中按服务定位器调用它
$sm = $this->getServiceLocator();
$myClass = $sm->get('Application\Service\MyClass');

无需设置DI。这对于Fieldsets / Form以及在何处/如何显示是必要的吗?

我尝试以这种方式注入我的Form和Fieldset:

    'service_manager' => array(
    'factories' => array(
        'Application\Form\CreateCostcenter' => function (\Zend\ServiceManager\ServiceLocatorInterface $sl) {
            $form = new \Application\Form\CreateCostcenter();
            $form->setServiceLocator($sl);
            return $form;
        },
        'Application\Form\CostcenterFieldset' => function (\Zend\ServiceManager\ServiceLocatorInterface $sl) {
            $fieldset = new \Application\Form\CostcenterFieldset();
            $fieldset->setServiceLocator($sl);
            return $fieldset;
        },
    ),
),

在我的控制器中调用时,注入适用于我的表单:

$form = $this->getServiceLocator()->get('Application\Form\CreateCostcenter');

但当然它不会将serviceManager传递给Fieldset。

无论如何,我不明白为什么必须有serviceManagerAwareness的配置,因为它只是通过实现它与其他类一起工作。 由于 ZF 2.1

,高级用法的文档中也没有任何提示

use an initializer (like Zend\ServiceManager\ServiceLocatorAwareInterface) to inject a specific object to all your forms/fieldsets/elements

0 个答案:

没有答案