Monday, 20 March 2017

Topic 12 - Service Container

Previously on laravel 4 , Service container was known as Inversion of Control (IoC) Container. As a Laravel developer, understanding and using the Service Container properly is a crucial part in mastering your craft, as it is the core of any Laravel application.

The term "Bind" is a common use of word that works with interfaces implementation , directories and other important things that make Laravel application run smoothly. Bind will produce a single Object that contains all of various bindings and it is very easy to retrieve them back or "resolve" them at any point of code.


Binding & Resolution

For the very basic, let say we have a certain Class DeliveryService that provides some particular service.

public class DeliveryService
{
    public function __construct()
    {
         //code here
    }

      public function doSomething()    
     {
         //code here
    }
How do we bind? 

Binding a service class is simple as line of code below

$this->app->bind('DeliveryService', \App\Services\DeliveryService::class);
Remember to always bind your services within the register method of your service providers.


How to use?

You can use the service binding using the example code:

$deliveryService = new \App\Services\DeliveryService();
$deliveryService->doSomething();
This will call the method inside DeliveryService class .


How do we resolve?

app()->make('DeliveryService')->doSomething();

With service container the code will look elegance and easy readable. Thus, the code will be much more cleaner.



References :

https://dotdev.co/understanding-laravel-service-container-bd488ca05280#.7g168fjgz
https://websanova.com/blog/laravel/10-reasons-why-laravel-is-better-than-codeigniter
https://laravel.com/docs/5.4/container#introduction

No comments:

Post a Comment