zend framework2 - use service locator for form or add the dependency and create an object? -
i getting hands on zend framework 2. have created user form , utilize form in controller can either include class in controller , create , object using new or can access form using service manager config access form.
i finding reasons using service manager here rather straight instantiating object. ideas??
the thought of service manager have ability replace form @ runtime. decoupling , reusability.
let's have module foo , there form foo\form\something. set foo module in application, need switch form else. if did $form = new foo\form\something in controller, have no simple alternative instantiate form. if register form under foo_form_something, bar module can overwrite service. foo_form_something not load foo\form\something bar\form\something. , there no alter required in controller.
there related coding style, inject form in controller instead of pulling via service manager. perhaps utilize this:
namespace mymodule\controller; class mycontroller { public function myaction() { $form = $this->getservicelocator()->get('foo_form_something'); } } but makes testing of controllers much harder. easier inject dependency:
namespace mymodule\controller; utilize foo\form\something somethingform; class mycontroller { protected $form; public function __construct(somethingform $foo) { $this->form = $foo } public function myaction() { $form = $this->form; } } and inject form in controller configuration:
namespace mymodule; class module { public function getcontrollerconfig() { homecoming array( 'factories' => array( 'mymodule\controller\mycontroller' => function($sm) { $form = $sm->getservicelocator()->get('foo_form_something'); $controller = new mymodule\controller\mycontroller($form); homecoming $controller; } ), ); } } zend-framework2 service-locator servicemanager
No comments:
Post a Comment