Sheikh Heera shares a good tip on how to use container events

It’s been quite a long time I’ve written an article on my blog, last time I’ve written about Laravel Form Validation Using Middleware and it’s about Laravel again. This time I’m going to discuss abour the Service Container (also known as IoC Container). As the title indicates that, this article is about using the event mechanism of the Service Container component that comes out of the box with Laravel framework.

In this case, I’m not going to give an introduction about Laravel framework but a little bit about the Service Container component and in short, it’s responsible for managing the class dependencies which performs dependency injection on run time. In other words, it injects dependent objects into a class automatically when a class needs them. If you are new to Laravel then please follow the link.

Anyways, let’s continue. So, the Service Container component allows us to bind class dependencies so that, when we need a class we may ask the Service Container component to give us an instance of that class and the Service Container component will give us an object instance of that class without any problem even if that class has other dependencies. For example, we may declare a binding like the following:

\App::bind('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app['HttpClient']);
});

In this case, when we need the instance of HelpSpot\API class, we can simply ask for it using the following code:

$api = \App::make('HelpSpot\API');

In this case, the Service Container component will give us the instance of the class and it’ll also inject the dependent HttpClient object into th