阅读(2406) (11)

Laravel 8 上下文绑定

2021-06-23 10:30:38 更新

有时你可能有两个类使用了相同的接口,但你希望各自注入不同的实现。例如, 有两个控制器可能依赖了 Illuminate\Contracts\Filesystem\Filesystem 契约。Laravel 提供了一个简单的,优雅的接口来定义这个行为:

use App\Http\Controllers\PhotoController;
use App\Http\Controllers\UploadController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;

$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');
          });