Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

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);
    });
}

( https://laravel.com/docs/9.x/octane#container-injection )

But when does one ever need to touch the App's Service Container anyway?

0 likes
6 replies
Ligonsker's avatar

@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)

Sinnbeck's avatar

@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.

1 like
Ligonsker's avatar

@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)

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Ligonsker Well lets say you have a service class (mail service) that sets the recipient email

$this->email = $email;

Now this class isnt flushed when the next user enters the applicaiton and that email from the previous user will still be set.

1 like

Please or to participate in this conversation.