We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
If you have a class you want to use in different places and which requires a configuration, don't be tempted do this:
<?php
public function index (Request $request)
{
$transistor = new Transistor(config('settings.key')) ;
$station = $transistor->getStation();
}
Much better is to bind it in the service provider (e.g. AppServiceProvider
):
<?php
$this->app->bind(Transistor::class, function() {
return new Transistor(config( 'settings.key')) ;
);
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:
<?php
public function index(Request $request, Transistor $transistor)
{
$station = $transistor->getStation();
}
It allows you to do fancy things such as setting up the class instances in a different way when you use them in testing:
<?php
$this->app->bind(Transistor::class, function() {
if (App::environment('testing')) {
return new Transistor(config( 'settings-testing.key')) ;
}
return new Transistor(config( 'settings.key')) ;
);
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.