Registering Services Quickly In Laravel

Posted on Updated on Laravel by Gergő D. Nagy

When binding services into the container, usually we use the register() method, which is the dedicated method for this. However, there is another quick way to bind services.

Let’s take a look, how do we use the register method usually:

public function register()
{
    $this->app->singleton(Contract::class, Service::class);

    $this->app->bind(OtherContract::class, function ($app) {
        return new OtherService($app);
    });
}

This is the generic way to register services, and we need to go this way when we want to customize the service a bit. However, when our service is quite simple, we can skip the register method, and use the $bindings and $singletons property:

public $bindings = [
    OtherContract::class => OtherService::class,
];

public $singletons = [
    Contract::class => Service::class,
];

Using this approach, we can clean up our register method a bit. This is useful when we are registering a bunch of different services, so the simpler ones, we can refactor to a property instead of populating the register method more.

You can find the documentation here: https://laravel.com/docs/master/providers

Need a web developer? Maybe we can help, get in touch!