3

我正在 Laravel 中练习,我发现了一个有用的方法“->withVariable($example)”,您可以在其中将变量用作刀片文件中的 $variable 名称。

请问A法和B法有区别吗?


方法一

在控制器中:

$a = 'test a';
$b = 'test b';
$c = 'test c';

return view('welcome')->withTest1($a)->withTest2($b)->withTest3($c);

鉴于:

$test1 // test a
$test2 // test b
$test3 // test c

方法B

在控制器中:

$a = 'test a';
$b = 'test b';
$c = 'test c';

return view('welcome', compact('a', 'b', 'c'));

鉴于:

$a // test a
$b // test b
$c // test c
4

1 回答 1

2

显然存在一些允许这种行为的讨厌的代码,请参阅Illuminate\View\View

    /**
     * Dynamically bind parameters to the view.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return \Illuminate\View\View
     *
     * @throws \BadMethodCallException
     */
    public function __call($method, $parameters)
    {
        if (static::hasMacro($method)) {
            return $this->macroCall($method, $parameters);
        }

        if (! Str::startsWith($method, 'with')) {
            throw new BadMethodCallException(sprintf(
                'Method %s::%s does not exist.', static::class, $method
            ));
        }

        return $this->with(Str::camel(substr($method, 4)), $parameters[0]);
    }

所以这个__call方法捕获了对视图实例的所有方法调用。调用view()->withTest('abc')将导致$method = 'withTest'并最终级联到仅调用的最后一行$this->with('test', 'abc')

所以最终结果没有区别。withTest链条看起来很讨厌。

恕我直言,应该避免使用这些魔术方法;要么compact()像你已经做的那样使用表格,或者简单地使用:

view('myview', [
    'foo' => 123,
    'bar' => 'abc'
]);
// or
view('myview')->with([
    'foo' => 123,
    'bar' => 'abc'
]);
// or
$foo = 123;
$bar = 'abc';
view('myview', compact('foo', 'bar'));
// or
view('myview')->with(compact('foo', 'bar'));

可悲的是,有多种可能性。

于 2020-01-23T23:59:42.943 回答