Laravel 组过滤器如何能够在没有 return 的情况下从闭包中获取值

How are Laravel Group Filters able to get the values from a closure without a return

我目前正在开发一个系统,我碰巧 运行 遇到了 Laravel 中调用的某个功能,我想知道它是如何工作的。

Route::group(array('before' => 'auth'), function()
{
  Route::get('user/account', 'UserController@account');
  Route::get('user/settings', 'UserController@settings');
  Route::get('post/create', 'PostController@create');
  Route::post('post/store', 'PostController@store');
  // ...
});

从上面的代码可以看出Laravel可以获取到所有的内部路由而无需返回任何路由

这是如何实现的?

提前致谢

这是使用堆栈完成的。我们来看看group()方法:

public function group(array $attributes, Closure $callback)
{
    $this->updateGroupStack($attributes);

    // Once we have updated the group stack, we will execute the user Closure and
    // merge in the groups attributes when the route is created. After we have
    // run the callback, we will pop the attributes off of this group stack.
    call_user_func($callback, $this);

    array_pop($this->groupStack);
}

首先,您传递的属性(如'before' => 'auth')将保存在$this->groupStack中。之后调用回调函数。

现在,当您执行 Route::get() 时,调用将在 createRoute 中结束,其中包含以下部分:

if ($this->hasGroupStack())
{
    $this->mergeGroupAttributesIntoRoute($route);
}

所以如果有任何组属性,它们将与路由合并。

组的回调函数执行后,组属性从栈中移除array_pop