Laravel Service Container and Service Providers

Laravel Service Container and Service Providers

Two concepts sit at the heart of every Laravel application: the service container and service providers. Once you understand them, a lot of Laravel's "magic" stops being magic. Here is how I think about them and how I use them.

What is the service container?

The service container is Laravel's tool for managing class dependencies and performing dependency injection. Instead of creating objects yourself with new everywhere, you ask the container for them, and it builds them for you, including whatever those objects depend on.

In many cases you don't need to configure anything. If a class depends only on other concrete classes, the container can resolve it automatically by reading the constructor's type hints. This is called automatic resolution (or auto-wiring).

class InvoiceController extends Controller
{
    public function __construct(
        protected InvoiceService $invoices
    ) {}
}

When Laravel builds this controller, it sees InvoiceService in the constructor, creates it (and its own dependencies), and passes it in.

How to use the service container

Binding a class or interface

Where auto-wiring isn't enough, for example when you type-hint an interface or need custom setup, you tell the container how to build it:

use App\Contracts\PaymentGateway;
use App\Services\StripeGateway;

$this->app->bind(PaymentGateway::class, function ($app) {
    return new StripeGateway(config('services.stripe.secret'));
});

With bind, you get a new instance every time it is resolved.

Singletons

If you want one shared instance for the whole request lifecycle, use singleton:

$this->app->singleton(PaymentGateway::class, function ($app) {
    return new StripeGateway(config('services.stripe.secret'));
});

Binding an interface to an implementation

For a simple mapping you can skip the closure:

$this->app->bind(PaymentGateway::class, StripeGateway::class);

Now any class that type-hints PaymentGateway receives a StripeGateway. Swapping implementations later means changing one line.

Resolving from the container

Most of the time, type-hinting in constructors or controller methods is enough. When you need to resolve something manually, you can use:

$gateway = app(PaymentGateway::class);
// or
$gateway = app()->make(PaymentGateway::class);

What is a service provider?

Service providers are the central place where a Laravel application is bootstrapped. Your own code, and Laravel's core services, are registered through them. When you ask "where do I put my container bindings?", the answer is: in a service provider.

Every provider has two main methods:

  • register(): only bind things into the container here. Don't use other services, because they may not be registered yet.
  • boot(): runs after all providers are registered, so you can use any service here, such as registering event listeners, view composers or macros.

How to use a service provider

Creating one

Generate a provider with Artisan:

php artisan make:provider PaymentServiceProvider

Adding bindings

namespace App\Providers;

use App\Contracts\PaymentGateway;
use App\Services\StripeGateway;
use Illuminate\Support\ServiceProvider;

class PaymentServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(PaymentGateway::class, function ($app) {
            return new StripeGateway(config('services.stripe.secret'));
        });
    }

    public function boot(): void
    {
        // Code that needs other services, after everything is registered
    }
}

Registering the provider

In recent Laravel versions, providers are listed in bootstrap/providers.php, and make:provider adds the new one automatically. In older versions you add it to the providers array in config/app.php.

return [
    App\Providers\AppServiceProvider::class,
    App\Providers\PaymentServiceProvider::class,
];

For a handful of small bindings, the existing AppServiceProvider is fine. When a feature grows, I give it its own provider so the setup stays easy to find.

How they fit together

The container is the toolbox that knows how to build your objects. Service providers are where you teach it how. Write your classes against interfaces, register the bindings in a provider, and let type-hints do the rest.

Tagged

No comments yet

Leave a comment

Security code

Comments are checked before they appear. See the privacy policy for how your data is used.