中间件中的 Laravel 依赖注入

2022-08-30 21:39:23

我使用的是Laravel-5.0的默认中间件,但我更改了句柄函数的签名,使其具有:Authentication

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

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

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

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

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...

有人能看到我做错了什么吗?

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


答案 1

您不能直接在 Request 中对方法执行依赖项注入,请在构造函数中执行此操作。handle

中间件由 调用,因此此处的任何注入都不起作用。call_user_func

<?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
  }
}

答案 2

不允许在此处更改方法签名。简单地说,你可以使用这样的东西:

public function handle($request, Closure $next) {

    // Get the bound object to this interface from Service Provider
    $authClient = app('App\Services\Contracts\AuthClientInterface');

    // Now you can use the $authClient
}

另外,您可以使用一种方法来实现这一点,请检查 - 给出的答案。__constructFrancis.TM


推荐