When does one ever inject the app's Service Container?
I just installed Octane and wanted to test it. One of the things written in the docs is that I should avoid injecting the application service container or HTTP request instance into the constructors of other objects
With the given following example:
use App\Service;
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(Service::class, function ($app) {
return new Service($app);
});
}
Imagine you are writing some service yourself, that you want to use in your application. The problem is that it needs to get several things from the config, or other values in its constructor. Then you can bind it in the service container which allows laravel to get it from the container instead of resolving it as new Service()
@Sinnbeck So the doc's example is for any Service that you write, not specifically the Service::class, because you actually extend the Service class whenever you write a new Service?
class MyServiceProvider extends ServiceProvider
And the docs just gave the entire Service Container as a general idea?
(Because in the link you posted, they aren't injecting the actual Service::class)
@Ligonsker I think that choosing the name service in the example is what threw you off. But a service is not the same as the service container. The service container is where you set up how to handle your sevice. A service can be anything, like the nexmo client in that example or similar. I used to have a mailgun client which was a wrapper for the official package.
@Sinnbeck Yes I thought it's some master container but now I understand it's just a generic name.
And the issue that the docs warn about is that, for example - because you now rely on the same instance of the class, then there might be cases where some piece of code tries to update some config values but the subsequent requests rely on the initial unchanged values? (I'm sure there are more examples)