What is Laravel Service Container? How it works?

What is Laravel Service Container? How it works?

Laravel Service Container
Laravel Service Container

 

Laravel framework comes with a powerful concept of the Laravel Service Container. Laravel has become one of the most popular web development frameworks today. To learn and start with the basic of Laravel framework – read this simple Laravel Tutorial.

Being open-source, it has unique modern features like Eloquent ORM, Query Builder, Service Container, Homestead, etc. These features are available in the Laravel Framework only. Through this laravel service container tutorial, we will discuss why do we need a service container and how to use it in our laravel projects?

 

What is Laravel Service Container?

Laravel Service Container is a powerful tool for laravel developers to bind and resolve concrete instances of classes and interfaces. Laravel service container also known as dependency injection container sits at the core of every laravel feature.

In simple terms, Laravel service container is a feature for developers to manage class dependencies and performing dependency injection.

The laravel service container is also known as laravel dependency injection container. This is because the core concept beneath service provider in laravel is dependency injection design pattern.

Dependency Injection is a design pattern in software development. Let’s understand it…

A Quick Introduction to Dependency Injection

In software application design, dependency injection is a technique whereby one object supplies the dependencies of another object.

A “dependency” is an object that can be used, for example, a service.

Dependency injection means that rather than being instantiated (“newed up”) within a class, each class’s dependencies will be injected in from the outside. This process occurs with the class’s constructor injection, which means an object’s dependencies are injected when it’s created.

Learn more about dependency injection here.

When an object or dependency is injected?

The dependency of an object is injected when an object is instantiated. (“constructed”). Dependency Injection minimizes the tight coupling between a class and its dependency. Dependency injection provides a developer with the flexibility of being configurable. 

Now, let’s take a simple example to practically understand Laravel service container and how it works.

Basic Laravel service container example :

Lets take an example of service container using dependency injection method. The dependency is injected through a class constructor, this process is called as constructor injection.

class UserEmailAlerts
{
protected $userEmailAlerts;
public function __construct(AlertsMailer $mailer)
{
$this->userEmailAlerts = $mailer;
}
public function welcome($user)
{
return $this->userEmailAlerts->mail($user->email, ‘Welcome!’);
}
}

Here, the UserEmailAlerts class expects an object of type AlertsMailer to be injected when it is instantiated, and its methods then refer to that instance.

The main advantage of dependency injection is that it gives developers the flexibility to change whatever identifier is injected.

 

If you are a beginner to Laravel Framework, then we recommend you to read the following topics:

 

The binding process educates the container how it should resolve objects.

Let’s understand how binding works in laravel? Read how Laravel request lifecycle.

Binding Classes to the Laravel Service Container

Essentially, the process of Binding a class to service container is actually informing the container that :

 “If a developer asks for an instance of Something, here’s the code to run in order to         instantiate one with the correct parameters and dependencies and then return it correctly.”

 

Example – Basic Service Container binding:

// In service provider
public function register()
{
    $this->app->bind(Logger::class, function ($app) {
          return new Something(‘\log\path\here’, ‘error’);
    });

}

Lets understand this qickly..

First, we’re running $this->app->bind(). $this->app is an instance of the container that’s always available on every service provider. The container’s bind() method is what we use to bind to the container.

The first parameter of bind() method is the “key” that we are binding to. Here we have used the FQCN (Fully Qualified Class Name) of the class. The second parameter asks the container what to do to resolve an instance of that
given bound key.

 

How a Laravel service container works?

The service container in laravel is the core concept of the framework, it’s used all over the Laravel.
So, it is important for developers to grasp and practice how Laravel service container actually works?

We have seen that whenever an object is injected into the class, it is internally handled and resolved by the laravel service container.

The service container fires an event each time it resolves an object. You can write code to listen this event using the resolving() method.

$this->app->resolving(function ($object, $app) {
// This is Called when container resolves object of any type…
});

$this->app->resolving(HelpSpot\API::class, function ($api, $app) {
// This is Called when container resolves objects of type “HelpSpot\API”…
});

 

What happens when an object is not resolved?

If in any case, the laravel service container failed to resolve the given object or class.
Then, the service container throws an exception as an instance of Psr\Container\NotFoundExceptionInterface

Conclusion

Now that we have learned that Laravel Service Container allows laravel developers to define rules for how classes in laravel are auto-loaded during the dependency injection process. Also, note that Laravel Service Container code resides inside the Service Provider class, which must be registered in the configuration file ../config/app.php

 

Leave a Reply

Your email address will not be published. Required fields are marked *