Actually, in my ZF2 project I've created base classes for models, forms and so on. For example: I noticed that I would probably need ServiceLocator in my models, so I created a class Application\Model\Base that implements the ServiceLocatorAwareInterface. This also applies to my forms.
I was thinking if that was the best way to do this or if I should pass the dependencies in the constructor. So I came with a problem today:
I have a form (Application\Form\Customer\Add) that needs to use the ServiceLocator in its constructor. But in this point, the ServiceLocator has not been set yet (the constructor is called before setServiceLocator()).
So, what do you think is the best way to solve this? Should I pass the dependencies by the constructor or continue using this approach that I'm actually using (and try to solve the customer form problem another way)?
ServiceManager
to Model constructor in theModule.php
, and passServiceManager
to Form constructor in the controller when you get instance from Form class. – Mohammad Mehdi Habibi