且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

中间件中的Laravel依赖注入

更新时间:2023-02-19 17:55:17

您不能直接在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
  }
}