在Laravel中,为什么在应用程序事件之前,Request :: segment()方法可以正常工作,而Route :: currentRouteName()却不能正常工作?

阿姆

在Laravel PHP Framework的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()不能正常工作?

艾伦·斯托姆(Alan Storm)

在建立和实例化应用程序对象之前,先建立和实例化请求对象。这意味着当应用程序的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;
}

您将通过对currentobject属性进行操作来看到它的工作原理该对象属性在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的核心系统代码findRoute直到实例化应用程序对象并触发事件后才调用该方法before即-当您的before观察员/听众开火时,Laravel不知道这条路线是什么。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章