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
Formdepends on aService. The first option is to inject dependencies:In this case, the
$formis unaware of the location of$serviceand 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 aFormobject. This is an example to inject aServiceinto aForm:Then you simply get the
Formfrom 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 🙂