在Laravel PHP Framework的app/filters.php
文件中,您可以找到应用程序的before
和after
事件,当我尝试将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
object属性进行操作来看到它的工作原理。该对象属性在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] 删除。
我来说两句