Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass parameters to the constructors through the Service Container?

I have a class that is responseible for calling a 3rd party payment solution.

As a part of this, there are various merchant id/shared secret parameters. Theses will depend on who's logged into the application.

The class I'm working with takes this info in the constructor when the class is built. Is there a way to pass this in the service provider, perhaps like this:

 $this->app->bind( 'App\BokaKanot\Interfaces\BillingInterface',function ($merchantId)
 {
    return new KlarnaBilling($merchantId);
 } );

If so, is it still possible to do this through a constructor or do I need to manaully use App:make. If I do have to use App::make, how can I not hide this inside my calling class?

Or should I refactor the class I'm using to not need this in the constructor, and perhaps have an init method?

like image 582
iKode Avatar asked Feb 07 '23 10:02

iKode


2 Answers

You can pass parameters to App::make and pass the parameters to the constructor like this:

$this->app->bind( 'App\BokaKanot\Interfaces\BillingInterface',
                   function( $app, array $parameters)
{
    //call the constructor passing the first element of $parameters
    return new KlarnaBilling( $parameters[0] );
} );

//pass the parameter to App::Make
App::make( 'App\BokaKanot\Interfaces\BillingInterface',  [ $merchantId ]  );
like image 178
Moppo Avatar answered Feb 10 '23 10:02

Moppo


On laravel 5.4 (https://github.com/laravel/framework/pull/18271), you need to use the method makeWith of the IoC container.

App::makeWith( 'App\MyNameSpace\MyClass',  [ $id ]  );

if you still use 5.3 or below, the above answers will work

like image 28
Lk77 Avatar answered Feb 10 '23 11:02

Lk77