如何在不关闭的情况下构建和初始化

How to build and initializers without closure

我有这个代码:

public function getFormElementConfig()
    {
        return array(
            'initializers' => array(
                'ObjectManagerInitializer' => function ($element, FormElementManager $formElements) {
                    if ($element instanceof ObjectManagerAwareInterface) {
                        /** @var ServiceLocatorInterface $serviceLocator */
                        $serviceLocator = $formElements->getServiceLocator();
                        $entityManager = $serviceLocator->get('doctrine.entitymanager.orm_default');

                        $element->setObjectManager($entityManager);
                    }
                },
            ),
        );
    }

This formElement config give me the Object manager for hydrators and Doctrine ObjectSelect in my forms when they implements ObjectManagerAwareInterface.

如何将其移出闭包?我没有任何线索,因为初始化器是自动的。我需要工厂吗?

到目前为止,我尝试创建这样的配置密钥

 'form_elements'   => array(// here because getFormElementConfig
    'initializers' => array(
        'ObjectManagerInitializer' => 'Application\Initializers\ObjectManagerInitializer',
    ),
),

然后创建对象

<?php
namespace Application\Initializers;

class ObjectManagerInitializer // implements or extends ??
{

}

但我不知道它需要哪个接口或架构,我不知道如何构建它。

初始化器只需要是可调用的,你可以通过声明 __invoke() 魔术方法使 class 可调用,然后你只需要将代码从你的匿名函数移动到该方法中,并且最后将初始化程序的 FQCN 添加到要附加到的服务管理器中。

所以你的 class 应该看起来像这样...

<?php
namespace Application\Initializers;

use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Zend\Form\FormElementManager;
use Zend\ServiceManager\ServiceLocatorInterface;

class ObjectManagerInitializer
{
    public function __invoke($element, FormElementManager $formElements) {
        if ($element instanceof ObjectManagerAwareInterface) {
            /** @var ServiceLocatorInterface $serviceLocator */
            $serviceLocator = $formElements->getServiceLocator();
            $entityManager = $serviceLocator->get('doctrine.entitymanager.orm_default');

            $element->setObjectManager($entityManager);
        }
    }
}

将 FQCN 添加到 module.config.php

中的表单元素管理器
'form_elements'   => array(
    'initializers' => array(
        'ObjectManagerInitializer' => 'Application\Initializers\ObjectManagerInitializer',
    ),
),