绑定基础知识几乎所有的服务容器绑定都是在服务提供者中完成的。目录结构如下:如果一个类不基于任何接口,那么就没有必要将它绑定到容器中。容器不需要被告知如何构造对象,因为它会使用PHP的反射服务来自动解析具体的对象。简单的绑定在一个serviceprovider中,可以通过$this->app变量访问容器,然后使用bind方法注册一个绑定,需要两个参数,第一个参数是我们要注册的类名或者接口名称,第二个参数是一个返回类实例的闭包:$this->app->bind('HelpSpot\API',function($app){returnnewHelpSpot\API($app->make('HttpClient'));});请注意,我们将容器本身作为参数传递给解析器,然后我们可以使用它来解析我们正在构建的对象的子依赖项。绑定一个单例方法,将一个只会被解析一次的类或接口绑定到容器中,然后对容器的后续调用将返回相同的对象实例:$this->app->singleton('HelpSpot\API',function($app){returnnewHelpSpot\API($app->make('HttpClient'));});绑定原始值你可能有一个接收注入类的类,你需要注入一个原生值比如Integer,你可以很容易地结合上下文注入这个类需要的任何值:$this->app->when('App\Http\Controllers\UserController')->needs('$variableName')->give($value);将接口绑定到实现服务容器的一个非常强大的特性是它能够将接口绑定到实现。我们假设有一个EventPusher接口和它的实现类RedisEventPusher。写好这个接口的RedisEventPusher实现后,就可以注册到服务容器中了:$this->app->bind('App\Contracts\EventPusher','App\Services\RedisEventPusher');这段代码告诉容器,当某个类需要实现EventPusher时,将注入RedisEventPusher。现在我们可以在构造函数或任何其他通过服务容器注入依赖项的地方执行EventPusher接口的依赖注入:useApp\Contracts\EventPusher;/***创建一个新的类实例**@paramEventPusher$pusher*@returnvoid*/publicfunction__construct(EventPusher$pusher){$this->pusher=$pusher;}有时上下文绑定假设我们可能有两个使用相同接口的类,但我们想在每个类中注入不同的实现,例如,两个控制器依赖于Illuminate\Contracts\Filesystem\Filesystem契约的不同实现。Laravel为此定义了一个简单、流畅的接口:useIlluminate\Support\Facades\Storage;useApp\Http\Controllers\VideoController;useApp\Http\Controllers\PhotoControllers;useIlluminate\Contracts\Filesystem\Filesystem;$this->app->when(PhotoController::class)->needs(Filesystem::class)->give(function(){returnStorage::disk('local');});$this->app->when(VideoController::class)->needs(Filesystem::class)->give(function(){returnStorage::disk('s3');});label在少数情况下,我们需要解析所有的Binding。例如,您正在构建一个接受多个不同Report接口实现的报告聚合器。注册Report实现后,可以通过tag方法为其分配标签:$this->app->bind('SpeedReport',function(){//});$this->app->bind('MemoryReport',function(){//});$this->app->tag(['SpeedReport','MemoryReport'],'reports');这些服务被标记后,可以通过标记方法轻松解析:$this->app->bind('ReportAggregator',function($app){returnnewReportAggregator($app->tagged('reports'));});扩展绑定extend方法允许修改解析器服务。例如,当服务被解析时,可以运行额外的代码来装饰或配置服务。extend方法接受一个闭包来返回修改后的服务:$this->app->extend(Service::class,function($service){returnnewDecoratedService($service);});
