首頁  >  文章  >  php框架  >  Laravel 中如何對 ORM 實現理解

Laravel 中如何對 ORM 實現理解

coldplay.xixi
coldplay.xixi轉載
2020-07-08 17:12:313928瀏覽

Laravel 中如何對 ORM 實現理解

什麼叫ORM

ORM,全称 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 實現理解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除