我不确定如何提出问题,因此请随时编辑。
我目前的情况如下:我有一个工厂课,可以实例化表格类。依赖注射(DI)是通过构造仪注入完成的。我的问题是,此表单元素具有一个教义对象莫尔特列克克式框,它需要faceby方法。对于此发现方法,我需要某个实体的ID,但是我无法将ID通过工厂类传递给表格。
我的问题是,我该如何处理这种情况?最好的方法是什么?
假设这是我的工厂课程:
class CustomerFormFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @return Form
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$em = $serviceLocator->get('DoctrineORMEntityManager');
return new CustomerForm($em);
}
}
我通过服务定位器获得表单:
$customerForm = $this->getServiceLocator()->get('CustomerForm');
如何将ID传递给服务定位器?而且,如果表单要素需要某个ID,难道是否会破坏DI和服务的目的?我应该这样做"经典"的方式并像这样实例化形式元素:
$customerForm = new CustomerForm(EntityManager $em, int $id);
我真的不确定我该怎么办,或者最好的处理方法是什么。
为了将选项插入您的表格中,您可以使用工厂类的CreationOptions
。
因此,让我们首先设置formelementmanager的配置(我们的表单元素的服务器)。
在您的Module.php
中:
use ZendModuleManagerFeatureFormElementProviderInterface;
class Module implements FormElementProviderInterface
{
// your module code
public function getFormElementConfig()
{
return [
'factories' => [
'myForm' => ModuleFormMyFormFactory::class
]
];
}
}
我们设置了应有的工厂,我们应该创建工厂,该工厂返回表格,包括其依赖关系。我们还插入可以在表单类中重新使用的选项。
use ZendServiceManagerFactoryInterface;
use ZendServiceManagerMutableCreationOptionsTrait;
use ZendServiceManagerServiceLocatorInterface;
class MyFormFactory implements FactoryInterface
{
use MutableCreationOptionsTrait;
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
*
* @return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
return new MyForm(
$serviceLocator->getServiceLocator()->get('DoctrineORMEntityManager'),
'MyForm',
$this->getCreationOptions()
);
}
}
使用ZF3时,最好使用
ZendServiceManagerFactoryFactoryInterface
而不是ZendServiceManagerFactoryInterface
,因为这是ZF3使用工厂的方式。在上面的示例中,我使用了ZF2(v2.7.6 ZendFramework/Zend-ServiceManager)版本。请参阅" zend servicemanager factoryinterface :: class"类上的评论,将其替换为ZF3版本。
所以现在,当我们在FormElementManager
类上调用::get('myForm', ['id' => $id])
时,您将获得一个MyForm
实例,该表单的选项将包含我们已通过的选项。
,您的表格看起来可能相似:
class MyForm extends ZendFormForm
{
public function __construct(
DoctrineCommonPersistenceObjectManager $entityManager,
$name = 'myForm',
$options = []
) {
parent::__construct($name, $options);
$this->setEntityManager($entityManager);
}
public function init () {
/** add form elements **/
$id = $this->getOption('id');
}
}
您还可以创建表单并设置EntityManager,但这全部取决于您。您不需要使用构造函数注入。
因此,您的控制器是一个exmaple:
$myForm = $this->getServiceManager()->get('FormElementManager')->get('myForm', ['id' => 1337]);
$options = $myForm->getOptions();
// your options: ['id' => 1337]
使用ZF2.5 或ZF3时,您的控制器中可能没有ServiceManager或定位器,因此您必须通过Factory将FormelementManager或表单类注射到控制器中。
如果您的表格中没有任何其他依赖关系,但是要设置选项,则无需为每个类创建一个工厂。您可以重新使用InvokableFactory::class
,因为这也将注入CreationOptions。