bruchowski bruchowski - 11 months ago 52
PHP Question

Does Laravel not have a factory style service container resolver?

Does the concept of a factory service exist in Laravel? I want to create a service provider that allows me to pass some additional configuration parameters.

I'm used to Silex where I can use the Pimple


Plenty of other frameworks like Angular2 have this feature as well, but I'm not seeing anything in the Laravel docs -- does this feature not exist in their IoC container?


I don't know Silex, but in Laravel you can create a service from the ioc container with additional parameters this way:

 App::bind( YourService::class, function($app)
    //create YourService passing Dependency from ioc container
    return new yourService( $app->make( Dependency::class ) );

Besides, if you need to pass these parameters dinamically from the calling code, you can let the ioc container receive them:

//bind the service accepting extra parameters
App::bind( YourService::class, function($app, array $parameters)
    //create YourService passing a parameter got from the calling code  
    return new YourService( $parameters[0] );
} );

And then pass the parameters to the ioc container:

//create the instance passing $myParameter 
$instance = App::make( YourService::class,  [ $myParameter ]  );