[英]zf2 ServiceManagerAwareInterface in Fieldset
在我的Zend \\ Form \\ Fieldset AddressFieldset中,它需要一個Zend \\ Db \\ TableGateway \\ AbstractTableGateway BundeslandTable來用於\\ Zend \\ Form \\ Element \\ Select()。
因此,我在此AddressFieldset中實現\\ Zend \\ ServiceManager \\ ServiceManagerAwareInterface並使用init()而不是__construct()。
並且在module.config.php中(不僅在“ form_elements”中進行了測試,還在“ service_manager”中進行了測試)
'form_elements' => array(
'factories' => array(
'MyFormway\Form\Fieldset\Address' => function($sm) {
$addressFieldset = new MyFormway\Form\Fieldset\AddressFieldset();
$addressFieldset->setServiceManager($sm);
return $addressFieldset;
}
),
),
在\\ Zend \\ Form \\ Form的init()中:
$this->add(array(
'type' => 'MyFormway\Form\Fieldset\Address',
'name' => 'address',
));
這會引發錯誤:
Zend\Form\FormElementManager::get was unable to fetch or create an instance for MyFormway\Form\Fieldset\Address
為什么zend無法獲取此Fieldset的實例?
編輯 - - - - - - - - - - - -
'form_elements' => array(
'factories' => array(
'MyFormway\Form\Fieldset\Address' => function($formElementManager) {
die('inna form_elements config');
$addressFieldset = new \MyFormway\Form\Fieldset\AddressFieldset();
$addressFieldset->setServiceManager($formElementManager->getServiceLocator());
return $addressFieldset;
}
),
),
因為我有Zend \\ Form \\ FormElementManager,所以我獲取了ServiceLocator ...也許不需要,因為所有XxxManager都擴展了Zend \\ ServiceManager \\ AbstractPluginManager,並且擴展了ServiceManager。 在FormElementManager和AbstractPluginManager中,沒有方法getServiceManager()。
但是我的問題是:不調用die()加上上面的錯誤。 是蟲子嗎? ...我代表一堵大牆:(
編輯 - - - - - - - - - - - -
它適用於表單,但不適用於字段集!!!
您可以快速檢查\\Invokable
是否被調用嗎? 一些專業的die()
調試就足夠了。
除此之外,您可能還會注入ServiceManager
。 在您提供的代碼中,實際上並沒有注入ServiceLocator
,而是注入了FormElementManager
。
$addressFieldset->setServiceManager($sm->getServiceManager());
以這種方式執行此操作被視為“不良實踐”。 您應該只注入您實際需要的東西。 假設您要注入整個經理,我假設您正在使用Doctrine,或者您需要訪問某些DB-Data。 像這樣做:
'Foo' => function ($formElementManager) {
$sl = $formElementManager->getServiceManager();
$fs = new FooFieldset();
$fs->setDbDependency(
$sl->get('MyDbDependency')
);
return $fs;
}
最后一點說明:添加字段集時,無需在$this->add()
添加'name' => 'foo'
,因為字段集的名稱將通過Fieldset __construct('name')
定義__construct('name')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.