在Laravel中,为什么使用“before”应用程序事件,“Request::segment()”方法工作正常,而“R


In Laravel, Why with the `before` application event, `Request::segment()` method works fine and `Route::currentRouteName()` does not?

>在Laravel PHP框架中,app/filters.php文件中,您可以在其中找到应用程序的beforeafter事件,当我尝试将Request::segment()方法与before事件一起使用时,它工作正常并且符合预期:

App::before(function($request)
{
    if (strtolower(Request::segment(1)) === 'something')
    {
        // code here..
    }
});

但是当我尝试使用这样的方法Route::currentRouteName()

App::before(function($request)
{
    if (strtolower(Route::currentRouteName()) === 'route_name')
    {
        // code here..
    }
});

它没有按预期工作。

为什么对于before应用程序事件,Request::segment()方法工作正常而Route::currentRouteName()方法无效?

在设置和实例化应用程序对象之前设置并实例化请求对象。 这意味着当应用程序的 before 事件触发时,Request 对象已填充其 URL 段和来自 PHP 本机请求超级全局变量的其他值。

路由器对象未应用程序对象之前有效设置和实例化。 如果您查看currentRouteName方法的定义

#File: vendor/laravel/framework/src/Illuminate/Routing/Router.php
public function currentRouteName()
{
    return ($this->current()) ? $this->current()->getName() : null;
}
public function current()
{
    return $this->current;
}

您将看到它通过对 current 对象属性进行操作来工作。 此对象属性在 findRoute 方法中设置。

#File: vendor/laravel/framework/src/Illuminate/Routing/Router.php
protected function findRoute($request)
{
    $this->current = $route = $this->routes->match($request);
    return $this->substituteBindings($route);
}

Laravel的核心系统代码在实例化应用程序对象并触发before事件之前不会调用findRoute方法。 也就是说,当你before观察者/侦听器触发时,Laravel还不知道路线是什么。

答案很简单。因为当前路由尚不可用。全局before筛选器在找到并调度匹配路由之前运行。

但是,该请求更早可用,因此Request::segment()工作正常。

你到底想完成什么?