如何使用照明/路由独立包注册中间件?

如何使用照明/路由独立包注册中间件?

问题描述:

Docs say to register middleware in app/Http/Kernel.php. How do I register middleware outside of the framework?

文档说要在 app / Http / Kernel.php code>中注册中间件。 如何在框架外注册中间件? p> div>

I'm not quite sure what you mean by outside of the framework but it pretty much comes down to this:

// Get your Illuminate\Routing\Router from somewhere.
// This could either be from the container instance or
// an instance you instantiated yourself somewhere
$router = new Illuminate\Routing\Router(....
// or in case you plan on doing this in a service provider for example
$router = $this->app['router'];

// Now you add your middleware using the following syntax
$router->middleware('name', My\Middleware::class);

// It's also possible to add a middleware group
$router->middlewareGroup('group_name', [
    'name',
    My\Other\Middleware::class
]);

// It's also possible to do this using the Laravel Facade's
Route::middleware(...
Route::middlewareGroup(...