I’m trying to use Service Manager on my entity class but I don’t know the best way to do that.
It’s easy on a controller because we can call service manager with : $this->getServiceLocator();
But, in my entity class, even if I implements ServiceLocatorAwareInterface i can retieve ServiceManager because my entity class isn’t call with the service manager :
So what is the best way :
1 – Pass serviceManager in my entity class from my controller
2 – Using ServiceManager to build my entity class
3 – … ?
To best understand my problem, that’s my code which doesn’t work :
My entity class:
class Demande extends ArraySerializable implements InputFilterAwareInterface {
/../
public function getUserTable() {
if (! $this->userTable) {
$sm = $this->getServiceLocator();//<== doesn't work !
$this->userTable = $sm->get ( 'Application\Model\UserTable' );
}
return $this->userTable;
}
I wouldn’t inject the ServiceManager into your model (although you can). I would rather get the ServiceManager to build your Model for you, and inject anything you need directly into the model.
Service Config:
Place any of your dependencies inside the Service Manager Config, and then use that to inject any dependencies into your models, services etc for you.
An example factory class if you want to use the factory method rather than closures:
DemandeFactory.php
An example Model you are trying to instantiate via the Service Manager.
Demande.php
In your Controller:
You could inject the SergiceManager/ServiceLocator into your models but then your models will depend on the ServiceLocator.