Laravel middleware dependency injection

I use Laravel-5.0 by default, AuthenticationMiddleware, but I changed the descriptor function signature to have:

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

I also registered AuthClientInterfacewith the service provider:

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 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'm doing wrong?

EDIT: I got the job by passing HelioAuthClientInterface to the middleware constructor. However, I thought that the IoC container would also add dependency to methods in addition to the constructor.

+4
source share
3 answers

handle , .

Middleware 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
  }
}
+13

Laravel IoC . IoC /, . , , , , .

IoC . IoC , . / : ?.

- , .

+3

. - :

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
}

, __construct , , - Francis.TM.

+2
source

Source: https://habr.com/ru/post/1629028/


All Articles