经过一番研究,我得到了解决方案。他们来了:
创建自定义调度程序
首先,您必须制作自己的自定义调度程序,我的是:
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];
}
}
在 Laravel 容器中注册您的自定义调度程序
然后,通过方法注册您自己的自定义调度程序。在注册所有路线后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;