1

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 factory method: https://github.com/silexphp/Pimple#defining-factory-services

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?

Moppo
  • 18,797
  • 5
  • 65
  • 64
bruchowski
  • 5,043
  • 7
  • 30
  • 46

1 Answers1

1

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 ]  );
Moppo
  • 18,797
  • 5
  • 65
  • 64
  • Gotcha, thank you -- it doesn't specify in the docs that you can pass a additional parameters to the bind closure, that helps a lot – bruchowski Jul 05 '16 at 07:18