我想知道Laravel如何实现雄辩的语法,以便可以静态调用第一个where子句 User::where()
User::where('id', 23)->where('email', $email)->first();
Run Code Online (Sandbox Code Playgroud)
他们有一个public static function where()和一个public function where()
调用where一个Eloquent模型确实涉及幕后发生的一点魔力.首先,举个例子:
User::where(’name’, ‘Joe’)->first;
Run Code Online (Sandbox Code Playgroud)
类扩展的类where上不存在静态方法.ModelUser
会发生什么,是__callStatic调用PHP魔术方法,然后尝试调用该where方法.
public static function __callStatic($method, $parameters)
{
$instance = new static;
return call_user_func_array([$instance, $method], $parameters);
}
Run Code Online (Sandbox Code Playgroud)
由于没有明确定义的用户函数被调用where,因此执行下一个__call定义的魔术PHP方法Model.
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return call_user_func_array([$this, $method], $parameters);
}
$query = $this->newQuery();
return call_user_func_array([$query, $method], $parameters);
}
Run Code Online (Sandbox Code Playgroud)
通过以下方式可访问常见的数据库相关方
$query = $this->newQuery();
Run Code Online (Sandbox Code Playgroud)
这将实例化一个新的Eloquent查询构建器对象,并且该where方法运行该对象.
所以,当你使用```User :: where()``你实际上使用的时候:
Illuminate\Database\Eloquent\Builder::where()
Run Code Online (Sandbox Code Playgroud)
看看在生成器类,看看大家已经习惯了使用普通雄辩的方法,如where(),get(),first(),update(),等.
Laracasts有一个非常深入(付费)的视频,讲述了Eloquent在幕后的工作方式,我建议这样做.