阅读(2411)
赞(7)
Laravel 8 上下文绑定
2021-06-23 10:30:38 更新
有时你可能有两个类使用了相同的接口,但你希望各自注入不同的实现。例如, 有两个控制器可能依赖了 IlluminateContractsFilesystemFilesystem
契约。Laravel 提供了一个简单的,优雅的接口来定义这个行为:
use AppHttpControllersPhotoController;
use AppHttpControllersUploadController;
use AppHttpControllersVideoController;
use IlluminateContractsFilesystemFilesystem;
use IlluminateSupportFacadesStorage;
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk('local');
});
$this->app->when([VideoController::class, UploadController::class])
->needs(Filesystem::class)
->give(function () {
return Storage::disk('s3');
});