The service provider — Discovery Training of Laravel 10

Service providers are an essential component in the initialization of a boostrap application. They will make it possible to register “services” which can then be called in the rest of the application through dependency injection or by using the container directly.

To save a service, it is possible to declare it in the function register() of a Service Provider.

    public function register(): void
    {
        $this->app->singleton('weather', function (Application $app) {
            return new WeatherApi(config('WEATHER_KEY'));
        });
    }

Once this service is registered, it can be used anywhere in the application using the global method app().

app('weather') // WeatherApi{}

Accessing a service will automatically instantiate the object as defined in the provider.

Dependency Injection

It is also possible to define the service using the class name rather than an arbitrary string.

    public function register(): void
    {
        $this->app->singleton(Weather::class, function (Application $app) {
            return new WeatherApi(config('WEATHER_KEY'));
        });
    }

This then allows you to take advantage of dependency injection. When Laravel tries to instantiate a class it will be able to look at the necessary dependencies. If a dependency corresponds to a service it knows, it will automatically inject the service in question.

class UserController extends Controller
{
    public function __construct(
        private WeatherApi $weather,
    ) {}
}

This can also be used for framework components as a replacement for facades.

class UserController extends Controller
{
    public function index(
        private Illuminate\Auth\AuthManager $auth,
    ) {
        $user = $auth->user();
        // ...
    }
}