中间件中的Laravel依赖注入 [英] Laravel Dependency Injection in Middleware

查看:357
本文介绍了中间件中的Laravel依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Laravel-5.0的默认Authentication中间件,但我将handle函数的签名更改为:

I am using Laravel-5.0's default Authentication Middleware, but I changed the signature of the handle function to have:

public function handle($request, Closure $next, AuthClientInterface $authClient)

我还在服务提供商中向AuthClientInterface注册了:

I also registered AuthClientInterface in a Service Provider with:

public function register()
{
    $this->app->bind('App\Services\Contracts\AuthClientInterface', function()
    {
        return new AuthClient(
            env('AUTH_SERVER_URL'),
            env('AUTH_SESSION_URL'),
            env('AUTH_CLIENT_ID')
        );
    });
}

但是,尽管如此,我仍然看到以下错误:

However, despite this, I am see the following error:

Argument 3 passed to HelioQuote\Http\Middleware\Authenticate::handle() 
must be an instance of 
HelioQuote\Services\Contracts\HelioAuthClientInterface, none given, 
called in C:\MyApp\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php on line 125 and defined...

有人可以看到我在做什么错吗?

Can anyone see what I am doing wrong?

我确实通过将HelioAuthClientInterface传递到中间件的构造函数中来使其工作.但是我认为IoC容器除了构造函数之外,还将注入对方法的依赖.

I did get it working by passing the HelioAuthClientInterface into the constructor of the middleware. However I thought the IoC container would also inject the dependency to methods in addition to the constructor.

推荐答案

您不能直接在Request中的handle方法上进行依赖项注入,而必须在构造函数中进行.

You cannot do dependency injection at handle method in a Request directly, do that in a constructor.

中间件由call_user_func调用,因此此处的任何注入均无效.

Middleware is invoked by call_user_func, so any injection here will not be work.

<?php

namespace App\Http\Middleware;

use Closure;
use App\Foo\Bar\AuthClientInterface; # Change this package name

class FooMiddleware
{
  protected $authClient;

  public function __construct(AuthClientInterface $authClient)
  {
    $this->authClient = $authClient;
  }

  public function handle(Request $request, Closure $next)
  {
    // do what you want here through $this->authClient
  }
}

这篇关于中间件中的Laravel依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆