“with anything”是如何工作的?在Laravel中传递变量到会话的方式


How works the "withANYTHING" way of passing variables to the session in Laravel?

在Laravel中,我知道

return Redirect::back()->with(['Foo'=>'Bar']);

等价于

return Redirect::back()->withFoo('Bar');

但是…它是如何工作的?我的意思是,创建一个新的函数withFoo来传递一个变量?这种行为在Laravel代码中定义在哪里?我在哪里可以托运?

它是如何实现的(来源):

public function __call($method, $parameters)
{
    if (Str::startsWith($method, 'with')) {
        return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
    }
    throw new BadMethodCallException("Method [$method] does not exist on Redirect.");
}

记住,当一个人试图调用一个无法访问的方法时,魔术方法__call被触发。第一个参数是方法的名称,然后是传递的参数。在这个特殊的例子中,RedirectResponse->with()被触发,设置flash数据:

public function with($key, $value = null)
{
    $key = is_array($key) ? $key : [$key => $value];
    foreach ($key as $k => $v) {
        $this->session->flash($k, $v);
    }
    return $this;
}