assumption: Event\Service\EventService
is my personal object that works with Event\Entity\Event
entities
This code works in an ActionController:
$eventService = $this->getServiceLocator()->get('Event\Service\EventService');
How can I get $eventService
in a Zend\Form\Form
in the same way?
You have two options if you have a dependency like this. In your case, a
Form
depends on aService
. The first option is to inject dependencies:In this case, the
$form
is unaware of the location of$service
and generally accepted as a good idea. To make sure you don't need to set up all the dependencies yourself each time you need aForm
, you can use the service manager to create a factory.One way (there are more) to create a factory is to add a
getServiceConfiguration()
method to your module class and use a closure to instantiate aForm
object. This is an example to inject aService
into aForm
:Then you simply get the
Form
from your service manager. For example, in your controller:A second option is to pull dependencies. Though it is not recommended for classes like forms, you can inject a service manager so the form can pull dependencies itself:
However, this second option couples your code with unnecessary couplings and it makes it very hard to test your code. So please use dependency injection instead of pulling dependencies yourself. There are only a handful of cases where you might want to pull dependencies yourself :)
You can just configure the form with all the options in the module.php. In the following code I:
Code:
And then in the controller the following line will populate your object with all needed dependencies
$form = $this->getServiceLocator()->get('my_form');
Use the form element manager to get the form in your controller:
Then in your form will become this