フィールドセットの init() 関数内にオブジェクト マネージャーを取得するために、ドキュメントに従いました 。最初は、変更する必要があることがわかりました。
public function setServiceLocator(ServiceLocator $sl)
に
public function setServiceLocator(ServiceLocatorInterface $sl)
そうしないと、エラーが発生しました:
setServiceLocator() must be compatible with that of Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()
呼び出す$this->getServiceLocator()
と、FormManager のインスタンスを取得します。さらに、 return を呼び出し$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
とにかく、認識を使用して他のスレッドを読むことはお勧めしません。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を設定する必要はありません。これはフィールドセット/フォームに必要ですか?どこで/どのように正確ですか?
私はこの方法でフォームとフィールドセットを注入しようとしました:
'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以降の高度な使用方法に関するヒントもドキュメントにありません。