我开始研究Laravel,但我不理解服务容器的概念。
它是如何工作的,开发者需要知道什么才能在Laravel中充分利用这个概念?
TL;DR服务容器是Application
对象:它扩展了Container
类,获得了容器的所有功能。
与手动创建对象相比,使用服务容器的优势在于:
在创建对象时管理类依赖关系的能力
您定义了应该如何在应用程序的一个点(绑定)中创建对象,每次您需要创建一个新实例时,只需将其询问给服务容器,它就会为您创建它,以及所需的依赖项
例如,不用new
关键字手动创建对象:
//every time we need YourClass we should pass the dependency manually
$instance = new YourClass($dependency);
您可以在服务容器上注册绑定:
//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 );
});
并通过服务容器创建一个实例,其中包含:
//no need to create the YourClass dependencies, the SC will do that for us!
$instance = App::make( YourClass::class );
接口与具体类的绑定
使用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 );
使用服务容器作为注册表
您可以在容器上创建和存储唯一的对象实例,并在以后将其取回:使用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');
Laravel容器为来自服务的完整应用程序创建实例(类)我们不需要为这样的应用程序创建instance
$myclass = new MyClass();
$mymethod = $myclass->myMethod();
应用程序::绑定
首先,我们将查看App
类的绑定静态方法。bind
只是将类instance
(对象)与应用程序绑定,仅此而已。
App::bind('myapp', function(){
return new MyClass();
});
现在,我们可以通过使用make
(App
类的静态方法)将该对象用于我们的应用程序。
$myclass = App::make(MyClass::class);
$mymethod = $myclass->myMethod();
应用程序::singleton
在上面的例子中,当我们要调用make
方法时,它每次都会生成类的新instance
,所以Laravel对Singleton
有很好的解决方案我们可以通过singleton
方法将object
绑定到我们的应用程序。
App::singleton(MyClass::class, function(){
return new MyClass();
});
我们可以用CCD_ 16方法解决。现在,我们总是从这个方法中收到完全相同的实例。
$myclass = App::make(MyClass::class);
$mymethod = $myclass->myMethod();
应用程序:实例我们可以将一个实例绑定到容器,并且我们将始终使用instance
方法返回完全相同的实例。
$myclass = new MyClass();
App::instance(MyClass::class, $myclass);
我们可以通过解决
$myclass = App::make(MyClass::class);
我们可以通过绑定接口
App::instance(MyClassInterface::class, new MyClass);
实现绑定
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
);
}
}
结论:服务容器有助于创建类或服务。