在Laravel中,为什么对应用程序事件before而言,Request :: segment()方法可以正常工作,而Route :: currentRouteName()却不能正常工作? [英] In Laravel, Why with the `before` application event, `Request::segment()` method works fine and `Route::currentRouteName()` does not?
问题描述
在Laravel PHP Framework的app/filters.php
文件中,您在其中找到了应用程序的before
和after
事件,当我尝试将Request::segment()
方法与before
事件一起使用时,它工作正常且符合预期:
In Laravel PHP Framework, app/filters.php
file, in which you find the before
and after
events for the application, when I tried to use Request::segment()
method with the before
event, it worked fine and as expected:
App::before(function($request)
{
if (strtolower(Request::segment(1)) === 'something')
{
// code here..
}
});
但是当我尝试使用Route::currentRouteName()
这样的方法时:
But when I tried to use Route::currentRouteName()
method like this:
App::before(function($request)
{
if (strtolower(Route::currentRouteName()) === 'route_name')
{
// code here..
}
});
它没有按预期工作.
为什么使用before
应用程序事件,Request::segment()
方法可以正常工作,而Route::currentRouteName()
不能正常工作?
Why with the before
application event, Request::segment()
method works fine and Route::currentRouteName()
does not?
推荐答案
在建立和实例化应用程序对象之前,先建立和实例化请求对象.这意味着当应用程序的before
事件触发时,Request对象已经填充了它的URL段和来自PHP本机请求超级全局变量的其他值.
The request object is setup and instantiated before the application object is setup and instantiated. This means the when the application's before
event fires, the Request object has been populated with its URL segments and other values from PHP's native request super globals.
未正确设置Router对象,并在应用程序对象之前实例化了该对象.如果您查看currentRouteName
方法的定义
The Router object is not competently setup and instantiated before the application object. If you look at the definition of the currentRouteName
method
#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
方法中设置的.
You'll see it works by operating on the current
object property. This object property is set in the findRoute
method.
#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不知道这条路线是什么.
Laravel's core system code does not call the findRoute
method until after the application object has been instantiated and the before
event fires. i.e. -- when your before
observer/listener fires, Laravel doesn't know what the route is yet.
这篇关于在Laravel中,为什么对应用程序事件before而言,Request :: segment()方法可以正常工作,而Route :: currentRouteName()却不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!