zend-framework2servicemanager

Passing dynamic data to the construct of a service invokable


I have the following invokables set in my application config

"service_manager":{
 "invokables":{
    "Dbmodel\\User":"Application\\DbModel\\UserModel",
    "Dbmodel\\App":"Application\\DbModel\\AppModel"
 }
}

So the theory is that I can call :

$userMdl = $e->getApplication()->getServiceManager()->get('DbModel\User');

And the result will be an instance the class Application\DbModel\UserModel. OK This is great, that works I imagine now my question is this:

In my user model I need to pass an integer to the __construct for an ID to load the model with database data.

Clearly I cannot do this with having my models as invokables as I never get a chance to pass the ID.

Is there a way to create a factory that you can supply an argument such as a user id for my situation to use with object instantiation.

An example would be using it in a controller to get a model based on a get request for a user based on id


Solution

  • One idea could be having a UserModelFactory retrievable from the service manager and use that to build, with a given method which takes the user id as parameter, the UserModel that you need