laravel Laravel中Service Container的概念是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37038830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:43:40  来源:igfitidea点击:

What is the concept of Service Container in Laravel?

phplaraveldesign-patternslaravel-5laravel-5.2

提问by Nello

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

我开始研究 Laravel,但我不明白服务容器的概念。

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

它是如何工作的,开发人员需要知道什么才能在 Laravel 中充分利用这个概念?

回答by Moppo

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

Laravel 中的服务容器是一个依赖注入容器和应用程序的注册中心

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 newkeyword:

例如,不是使用new关键字手动创建对象:

//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:

使用 Laravel 自动依赖注入,当应用程序的某些部分(即控制器的构造函数)需要接口时,服务容器会自动实例化一个具体的类。更改绑定上的具体类,将更改通过您的所有应用程序实例化的具体对象:

//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::instancemethod to make the binding, and thus using the container as a Registry.

您可以在容器上创建和存储唯一的对象实例,并在以后取回它们:使用App::instance方法进行绑定,从而将容器用作注册表。

// 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 Applicationobject: it extends the Containerclass, getting all the container's funtionalities

最后一点,服务容器本质上是Application对象:它扩展了Container类,获得了容器的所有功能

回答by Paresh Barad

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

Laravel 容器从服务(类)为完整应用程序创建实例我们不需要instance为我们的应用程序创建像

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

App::bind

应用::绑定

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

首先,我们来看一下bindApp类的静态方法。bind只是将您的类instance(对象)与应用程序绑定,仅此而已。

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

Now, we can use this object for our application by using makea static method of Appclass.

现在,我们可以通过使用类make的静态方法将此对象用于我们的应用程序App

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

App::singleton

应用::单身

In above example when we are going to call makemethod then its generate every time new instanceof class, So Laravel have pretty solution for SingletonWe can bind an objectto our application by singletonmethod.

在上面的例子中,当我们要调用make方法时,它会在每次instance类的new时生成,所以 Laravel 有很好的解决方案,Singleton我们可以object通过singleton方法将一个绑定到我们的应用程序。

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

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

我们可以通过make方法解决。现在,我们总是从这个方法收到完全相同的实例。

$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 instancemethod.

App::instance 我们可以将一个实例绑定到容器,并且我们将始终使用instance方法返回完全相同的实例。

$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

Yaa,我们有一个问题,我们如何在我们的应用程序中实现绑定?我们可以在我们的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.

结论:服务容器有助于创建类或服务的对象。