美文网首页
43. 服务容器 上下文绑定

43. 服务容器 上下文绑定

作者: 独步天堂 | 来源:发表于2017-10-05 21:49 被阅读6次

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

    use Illuminate\Support\Facades\Storage;
    use App\Http\Controllers\PhotoController;
    use App\Http\Controllers\VideoController;
    use Illuminate\Contracts\Filesystem\Filesystem;
    
    $this->app->when(PhotoController::class)
              ->needs(Filesystem::class)
              ->give(function () {
                  return Storage::disk('local');
              });
    
    $this->app->when(VideoController::class)
              ->needs(Filesystem::class)
              ->give(function () {
                  return Storage::disk('s3');
              });
    

    相关文章

      网友评论

          本文标题:43. 服务容器 上下文绑定

          本文链接:https://www.haomeiwen.com/subject/wpwkyxtx.html