您好,欢迎访问一九零五行业门户网

Laravel 中如何对 ORM 实现理解

什么叫ormorm,全称 object-relational mapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在操作具体的业务对象时,就不需要再去和复杂的sql语句打交道,只需简单的操作对象的属性和方法即可。
orm 实现方式两种最常见的实现方式是 activerecord 和 datamapper (laravel 中使用的是前者)
我们先来理解两个魔法函数 __call() 和 __callstatic()class test{ //动态调用的时候 没有找到此函数 则执行__call() 方法 public function __call($method, $parameters){ echo 22222222222; return (new rest)->$method(...$parameters); } //静态调用的时候 没有找到此函数 则执行__callstatic()方法 public static function __callstatic($method, $parameters){ echo 1111111111; return (new static)->$method(...$parameters); }}class rest{ public function foo($name , $age){ echo 333; dump($name,$age); }} //先调用了__callstatic(), 在调用__call(), 然后调用 foo(); test::foo('张三',17); //只调用了 __call(), 然后调用 foo(); (new test())->foo('李四',16);die;
理解了前面两个魔法函数 对于laravel eloqument orm 中的难点 也就理解了,我们来看一下model中的源码
/** * handle dynamic method calls into the model. * * @param string $method * @param array $parameters * @return mixed */public function __call($method, $parameters){ if (in_array($method, ['increment', 'decrement'])) { return $this->$method(...$parameters); } return $this->newquery()->$method(...$parameters);} /** * handle dynamic static method calls into the method. * * @param string $method * @param array $parameters * @return mixed */public static function __callstatic($method, $parameters) { return (new static)->$method(...$parameters); }
new static 返回的是调用者的实例, new self() 返回的是自身实例
使用eloqument 查询的时候
$list = politician::where('party_id', 1)->count();
where 方法不在 model中 会先执行callstatic()函数 获取 app\models\politician 实例 ,再执行 call() , 在$this->newquery() 返回实例中寻找where() count()等方法。
细看一下 newquery() 方法 这里面返回的实例。 理解了这两个魔术函数 对laravel 中 orm的实现的难点就攻克了。
laravel 中的查询构造器$list = db::table('categoty')->get();
eloquent orm 实际上是对 查询构造进行了一次封装,可以更方便的去操作。 查询构造器的源码大家有兴趣的话可以看一看,谢谢。
相关学习推荐:laravel        
以上就是laravel 中如何对 orm 实现理解的详细内容。
其它类似信息

推荐信息