#development #laravel #pattern #php

If you have a class you want to use in different places and which requires a configuration, don't be tempted do this:

1public function index (Request $request)
2{
3    $transistor = new Transistor(config('settings.key')) ;
4    $station = $transistor->getStation();
5}

Much better is to bind it in the service provider (e.g. AppServiceProvider):

1$this->app->bind(Transistor::class, function() {
2    return new Transistor(config( 'settings.key')) ;
3);

Once it's bound, you can just inject it in e.g. a method by providing it as an extra method argument with a type-hint:

1public function index(Request $request, Transistor $transistor)
2{
3    $station = $transistor->getStation();
4}

It allows you to do fancy things such as setting up the class instances in a different way when you use them in testing:

1$this->app->bind(Transistor::class, function() {
2    if (App::environment('testing')) {
3        return new Transistor(config( 'settings-testing.key')) ;
4    }
5
6    return new Transistor(config( 'settings.key')) ;
7);