我需要有一个中间件目前发现的控制器和行动,这样我就可以做一些验证。但我发现它是不可能的,因为管道就像是Middleware1 - > Middleware2->做调度 - >控制器@行动() - > Middleware2 - > Middleware1。
因此,调度之前,我不能得到的路由信息。这绝对不是$控权后,把它做好>动作()。
我做了一些研究,发现这一点。
$allRoutes = $this->app->getRoutes();
$method = \Request::getMethod();
$pathInfo = \Request::getPathInfo();
$currentRoute = $allRoutes[$method.$pathInfo]['action']['uses'];
但是,像app/role/1
访问URI时,这是行不通的,因为$allRoutes
只有app/role/{id}
代替app/role/1
的指数。
有没有这方面有任何解决方法吗?
做一些研究之后,我得到了解决。在这里,他们去:
首先,你必须使自己的自定义调度员,我的是:
App\Dispatcher\GroupCountBased
存储为:
app/Dispatcher/GroupCountBased.php
下面是GroupCountBased
的内容:
<?php namespace App\Dispatcher;
use FastRoute\Dispatcher\GroupCountBased as BaseGroupCountBased;
class GroupCountBased extends BaseGroupCountBased
{
public $current;
protected function dispatchVariableRoute($routeData, $uri) {
foreach ($routeData as $data) {
if (!preg_match($data['regex'], $uri, $matches)) continue;
list($handler, $varNames) = $data['routeMap'][count($matches)];
$vars = [];
$i = 0;
foreach ($varNames as $varName) {
$vars[$varName] = $matches[++$i];
}
// HERE WE SET OUR CURRENT ROUTE INFORMATION
$this->current = [
'handler' => $handler,
'args' => $vars,
];
return [self::FOUND, $handler, $vars];
}
return [self::NOT_FOUND];
}
}
然后,通过注册方法singleton()
自己定制的调度员。为此,您注册的所有路由后!就我而言,我在bootstrap/app.php
添加自定义的调度员这一行后:
require __DIR__.'/../app/Http/routes.php';
这是什么样子:
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
require __DIR__.'/../app/Http/routes.php';
// REGISTER YOUR CUSTOM DISPATCHER IN LARAVEL CONTAINER VIA SINGLETON METHOD
$app->singleton('dispatcher', function () use ($app) {
return FastRoute\simpleDispatcher(function ($r) use ($app) {
foreach ($app->getRoutes() as $route) {
$r->addRoute($route['method'], $route['uri'], $route['action']);
}
}, [
'dispatcher' => 'App\\Dispatcher\\GroupCountBased',
]);
});
// SET YOUR CUSTOM DISPATCHER IN APPLICATION CONTEXT
$app->setDispatcher($app['dispatcher']);
注:我知道这是不优雅,因为
dispatch
中间件执行后调用,您必须手动派遣您的调度员。
在你的中间件,你handle
方法里面,这样做:
app('dispatcher')->dispatch($request->getMethod(), $request->getPathInfo());
例:
public function handle($request, Closure $next)
{
app('dispatcher')->dispatch($request->getMethod(), $request->getPathInfo());
dd(app('dispatcher')->current);
return $next($request);
}
为了让您的当前路径:
app('dispatcher')->current;
我找到了正确的答案这个问题。我错过了一个名为routeMiddleware()
的Application
一个方法。此方法注册其被分派之后调用的特定路线的中间件。因此,只要使用$app->routeMiddleware()
注册你的中间件。并获得中间件通过$request->route()
匹配的路由信息。