我在Laravel中练习,发现了一个有用的方法“-> withVariable($ example)”,您可以在刀片文件中使用Variable作为$ 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
在控制器中:
$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
显然,存在一些讨厌的代码可以实现这种行为,请参见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'));
可悲的是,有很多可能性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句