Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 67 ยท Routing and Controllers

Service Providers, Facades and Contracts

Learn how Laravel boots through service providers, why register and boot are separate, how facades work via __callStatic, and what contracts are for.

Every Laravel feature you use, from the router to the mailer, is wired into the framework by a service provider. A provider is a class with one job: tell the service container what it can build, and run any start-up code that needs those pieces. Your own application has a provider too (App\Providers\AppServiceProvider), and it is the right place for your bindings, event listeners and global settings.

Facades are the other half of this lesson. They are the static-looking calls such as Cache::get('key') or Route::get('/', ...). Despite the syntax, they are not static methods in the usual sense. Each facade forwards the call to an object that the container builds, which means you get short, readable code and the object can still be swapped for a fake in tests. Finally, contracts are the interfaces behind those objects, which you can type-hint when you want to depend on the behavior and not on a particular class.

Laravel code cannot run on this site, so the real framework snippets below are read-only. Each runnable example is a plain-PHP stand-in that follows the same idea in a few dozen lines, and the lesson says which is which.

What a service provider looks like

Generate one with Artisan:

Terminal
php artisan make:provider BillingServiceProvider

The command creates the class and, in a new Laravel 13 application, also adds it to bootstrap/providers.php. That file is nothing more than a list of class names; Laravel reads it during start-up.

PHP
<?php

// bootstrap/providers.php
return [
    App\Providers\AppServiceProvider::class,
    App\Providers\BillingServiceProvider::class,
];

A provider has two methods that matter:

PHP
<?php

namespace App\Providers;

use App\Services\InvoiceNumberGenerator;
use Illuminate\Support\ServiceProvider;

class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(InvoiceNumberGenerator::class, function ($app) {
            return new InvoiceNumberGenerator(config('billing.prefix'));
        });
    }

    public function boot(): void
    {
        // Safe to use any other service here.
        view()->share('companyName', config('app.name'));
    }
}

Packages you install with Composer register their own providers through package auto-discovery, so you rarely list them yourself. Package auto-discovery is covered in Packages and Extending Laravel.

register versus boot

The rule is simple and the reason matters.

  • register() may only put things into the container. Do not resolve other services, read from the database, or use routes, views or events here. At this moment other providers have not registered yet, so the service you want may not exist.
  • boot() runs after every provider has registered. Anything is available, so this is where you attach listeners, define gates, share data with views or add validation rules.
sequenceDiagram
    participant App as Application
    participant A as AppServiceProvider
    participant B as BillingServiceProvider
    App->>A: register()
    App->>B: register()
    Note over App: all bindings now exist
    App->>A: boot()
    App->>B: boot()

Laravel registers every provider first, then boots them all, so boot() can use bindings from any provider.

The next example is a stand-in, not Laravel: a tiny container and an Application that registers and boots provider classes in two passes. The ReportProvider deliberately depends on a binding owned by a provider that comes later in the list.

PHP register then boot, in two passes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

ReportProvider registers first but only stores a recipe for Reporter; the recipe asks for Clock later, when boot() runs and ClockProvider has long since registered. That is exactly why register() should bind and boot() should use. The last lines show what happens when you resolve too early: nothing is bound yet.

Deferred providers

Some providers are only needed now and then, such as one that sets up a rarely used PDF generator. A provider that only binds things can be marked as deferred. It implements Illuminate\Contracts\Support\DeferrableProvider and lists what it provides:

PHP
<?php

use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\ServiceProvider;

class PdfServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register(): void
    {
        $this->app->singleton(PdfRenderer::class, fn () => new PdfRenderer());
    }

    /** @return list<class-string> */
    public function provides(): array
    {
        return [PdfRenderer::class];
    }
}

Laravel then skips the provider on normal requests and registers it the first time something asks the container for PdfRenderer. A deferred provider should not rely on boot() to do work for the rest of the application, because it might never run. Laravel keeps a generated manifest of deferred providers in bootstrap/cache/services.php, so it knows which provider to load without instantiating them.

How a facade works

A facade is a class that extends Illuminate\Support\Facades\Facade and defines one method, getFacadeAccessor(), returning a container key. When you call a static method that does not exist on the class, PHP calls the magic __callStatic() (see magic methods). The base Facade class then resolves the object from the container and calls the method on that object.

PHP
<?php

// Real Laravel, simplified: what Cache::get('visits') does
$store = app('cache');          // the container builds (or reuses) the cache manager
return $store->get('visits');   // the call is forwarded to a normal object
flowchart LR
    C["Cache::get('visits')"] --> F["Facade::__callStatic"]
    F --> A["getFacadeAccessor()<br/>returns 'cache'"]
    A --> K["Container resolves<br/>the cache manager"]
    K --> M["manager->get('visits')"]

A facade is a thin static front. The real work happens on an object that the container resolves.

The stand-in below does the same with a Facade base class, a container and two cache classes. It also shows the feature that makes facades testable: swap() replaces the object behind the facade.

PHP A mini facade over a container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

visitCount() has no idea whether it talks to a real cache or a spy. In real Laravel you get the same effect with Cache::shouldReceive(...), and many facades have a fake() method (Mail::fake(), Queue::fake(), Storage::fake()), which swaps in a recording double. The faking and mocking lesson builds on this.

Facades or dependency injection?

Both reach the same objects, so the choice is mostly style. Facades are short and available anywhere, including Blade views and route files. Constructor injection makes a class's dependencies visible in its signature, which helps when a class grows. Because a facade is easy to call from anywhere, a class can quietly collect ten of them; if you notice that, move to constructor injection. Laravel's helper functions such as cache(), config() and auth() are a third spelling of the same thing.

Contracts

A contract is one of Laravel's interfaces under Illuminate\Contracts, for example Illuminate\Contracts\Cache\Repository or Illuminate\Contracts\Mail\Mailer. The concrete classes implement them, and the container binds the contract to the implementation. Type-hint the contract when you want to say "give me anything that can do this":

PHP
<?php

use Illuminate\Contracts\Cache\Repository;

class VisitCounter
{
    public function __construct(private Repository $cache) {}

    public function hit(): int
    {
        return $this->cache->increment('visits');
    }
}

You get the same object that Cache::store() returns, but your class now depends only on an interface. This is the same idea as interface bindings in the container and the abstract classes and interfaces lesson.

Real-time facades

You can turn any class into a facade on the fly by putting Facades in front of its fully qualified name in a use statement:

PHP
<?php

use Facades\App\Services\InvoiceNumberGenerator;

// Resolved from the container, but called statically:
$number = InvoiceNumberGenerator::next();

Laravel generates the facade class when it is first used. It is handy for testing, since the class becomes swappable without writing a facade by hand, but use it sparingly: ordinary injection is clearer.

Common mistakes

  • Resolving other services inside register() (see the "Too early" output above).
  • Putting application logic into providers. They are for wiring and start-up, not business rules.
  • Forgetting to add a new provider to bootstrap/providers.php when you create the file by hand.
  • Doing slow work in boot(). It runs on every request, so keep it light.
  • Assuming facades are real static methods. They cannot be mocked as static code; they work because of an object behind them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should a service provider's register() method do?

    At register time other providers may not have registered yet. Bind recipes here and use them in boot(), which runs after every provider has registered.
  2. 2. Where does Laravel 13 read the list of application providers?

    bootstrap/providers.php returns an array of provider class names. Package providers are added through auto-discovery.
  3. 3. How does Cache::get('x') reach a real object?

    Facade::__callStatic resolves the object named by getFacadeAccessor() from the container and forwards the method call, which is also why the object can be swapped in tests.
  4. 4. When would you mark a provider as deferred?

    A deferred provider implements DeferrableProvider and declares provides(). Laravel registers it only when one of those bindings is first requested.

Summary

  • A service provider wires services into the container; your own bindings usually go in AppServiceProvider.
  • register() only binds; boot() runs after all providers registered and may use any service.
  • Providers are listed in bootstrap/providers.php; packages register through auto-discovery.
  • Deferred providers (DeferrableProvider plus provides()) load on demand.
  • A facade forwards static-looking calls to a container object through __callStatic, which is what makes fake() and shouldReceive() possible.
  • Contracts are Laravel's interfaces; type-hint them to depend on behavior, and use real-time facades sparingly.

Next: Blade Templates