Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the concept of Service Container in Laravel?

I am starting to look into Laravel but I don't understand the concept of Service Container.

How does it work and what do developers need to know to fully utilize this concept in Laravel?

like image 535
Nello Avatar asked May 04 '16 22:05

Nello


People also ask

What is a service container used for?

What is a Service Container? A Service Container (or dependency injection container) is simply a PHP object that manages the instantiation of services (i.e. objects).

What is service container and service provider in Laravel?

Service container is the place our application bindings are stored. And the service providers are the classes where we register our bindings to service container. In older releases of Laravel, we didn't have these providers and people were always asking where to put the bindings.

What is the use of service provider in Laravel?

Service providers are the central place to configure your application. If you open the config/app. php file included with Laravel, you will see a providers array. These are all of the service provider classes that will be loaded for your application.

What is the IoC container job in Laravel?

The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.


2 Answers

The Service Container in Laravel is a Dependency Injection Container and a Registry for the application

The advantages of using a Service Container over creating manually your objects are:

Ability to manage class dependencies on object creation

You define how a object should be created in one point of the application (the binding) and every time you need to create a new instance, you just ask it to the service container, and it will create it for you, along with the required dependencies

For example, instead of creating objects manually with the new keyword:

//every time we need YourClass we should pass the dependency manually
$instance = new YourClass($dependency);

you can register a binding on the Service Container:

//add a binding for the class YourClass 
App::bind( YourClass::class, function()
{
    //do some preliminary work: create the needed dependencies
    $dependency = new DepClass( config('some.value') );

    //create and return the object with his dependencies
    return new YourClass( $dependency );
});

and create an instance through the service container with:

//no need to create the YourClass dependencies, the SC will do that for us!
$instance = App::make( YourClass::class );

Binding of interfaces to concrete classes

With Laravel automatic dependency injection, when an interface is required in some part of the app (i.e. in a controller's constructor), a concrete class is instantiated automatically by the Service Container. Changing the concrete class on the binding, will change the concrete objects instantiated through all your app:

//everityme a UserRepositoryInterface is requested, create an EloquentUserRepository 
App::bind( UserRepositoryInterface::class, EloquentUserRepository::class ); 

//from now on, create a TestUserRepository 
App::bind( UserRepositoryInterface::class, TestUserRepository::class );

Using the Service Container as a Registry

You can create and store unique object instances on the container and get them back later: using the App::instance method to make the binding, and thus using the container as a Registry.

// Create an instance.
$kevin = new User('Kevin');

// Bind it to the service container.
App::instance('the-user', $kevin);

// ...somewhere and/or in another class...

// Get back the instance
$kevin = App::make('the-user'); 

As a final note, essentially the Service Container -is- the Application object: it extends the Container class, getting all the container's funtionalities

like image 186
Moppo Avatar answered Oct 13 '22 02:10

Moppo


Laravel container create instance for full application from services(class) We don't need to create instance for our application like

$myclass = new MyClass();
$mymethod = $myclass->myMethod();

App::bind

First, We are going look bind static method of App class. bind is just binding your class instance(object) with an application, nothing more.

App::bind('myapp', function(){
    return new MyClass();
});

Now, we can use this object for our application by using make a static method of App class.

$myclass = App::make(MyClass::class);
$mymethod = $myclass->myMethod();

App::singleton

In above example when we are going to call make method then its generate every time new instance of class, So Laravel have pretty solution for Singleton We can bind an object to our application by singleton method.

App::singleton(MyClass::class, function(){
    return new MyClass();
});

We can be resolved by make method. Now, we have always received the exact same instance from this method.

$myclass = App::make(MyClass::class);
$mymethod = $myclass->myMethod();

App::instance We can bind an instance to the container and we will always return the exact same instance using instance method.

$myclass = new MyClass();
App::instance(MyClass::class, $myclass);

We can be resolved by

$myclass = App::make(MyClass::class);

We can bind interface by

App::instance(MyClassInterface::class, new MyClass);

Implementation Binding

Yaa, We have a question, How can we implement binding in our application? We can implement binding in our AppServiceProvider

app/Providers/AppServiceProvider.php

namespace App\Providers;

use App\SocialProvider;
use App\TwitterSocialProvider;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
  /**
   * Bootstrap any application services.
   *
   * @return void
   */
   public function boot()
  {

  }

   /**
   * Register any application services.
   *
   * @return void
   */
   public function register()
   {
      $this->app->bind(
        MyClassInterface::class,
        MyClass::class
      );
  }
}

Conclusion: Service container helps to create object of class or services.

like image 33
Paresh Barad Avatar answered Oct 13 '22 00:10

Paresh Barad