Implementation of dependency injection in Laravel 6 middleware
1. Check the existing code, which is implemented based on the function app. The app function returns the service container instance. Unable to jump to the corresponding method by clicking getByName() . as shown in Figure 1
getByName($decrypt['name']);
// ...
return $next($request);
}
}
2. Refer to the automatic injection of the service container. You can simply inject the dependencies that require container resolution, including controllers, event listeners, queue tasks, middleware, etc. In fact, this is how most objects should be parsed by the container.
3. Reference URL:https://stackoverflow.com/questions/35439234/laravel-dependency-injection-in-middleware
4. Implementation based on constructor. You can jump to the corresponding method by clicking getByName(). as shown in Figure 2
protected $themeService;
public function __construct(ThemeService $themeService)
{
$this->themeService = $themeService;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$theme = $this->themeService->getByName('vogue');
}

