這篇文章帶給大家的內容是關於Laravel原始碼解析之model(程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
提前預祝猿人們國慶快樂,吃好、喝好、玩好,我會在電視上看著你們。
根據單一責任開發原則來講,在laravel的開發過程中每個表都應建立一個model對外服務和呼叫。類似這樣
namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'users'; }
Laravel的資料運算分成兩種
DB facade
Eloquent ORM
它們除了有各自的特色外,基本的資料操作都是透過 Illuminate\Database\Query\Builder
呼叫方法去完成整個SQL。你也可以幫Builder這個類別作為整個SQL操作的基底類別。這個類別涵蓋了以下的操作方法(部分展示)
方法 |
---|
public function select($columns = ['*']) |
# public function selectSub($query, $as) |
# public function selectRaw($expression, array $bindings = []) |
public function fromSub($query, $as) |
public function fromRaw($expression, $bindings = []) |
public function addSelect($column) |
public function distinct() |
public function from ($table) |
public function join($table, $first, $operator = null, $second = null, $type = 'inner', $其中 = false) |
public function joinWhere($table, $first, $operator, $second, $type = 'inner') |
public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) |
public function leftJoin($table, $first, $operator = null, $second = null) |
# public function where($column, $operator = null, $value = null, $boolean = 'and')
|
public function orWhere( $column, $operator = null, $value = null) |
public function whereRaw($sql, $bindings = [], $boolean = 'and' ) |
public function whereIn($column, $values, $boolean = 'and', $not = false) |
public function orWhereIn($column, $values) |
DB::table('user')->get();
Illuminate\Foundation\Application -> registerCoreContainerAliases()
public function registerCoreContainerAliases() { foreach ([ ... 'encrypter' => [\Illuminate\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\Encrypter::class], 'db' => [\Illuminate\Database\DatabaseManager::class], 'db.connection' => [\Illuminate\Database\Connection::class, \Illuminate\Database\ConnectionInterface::class], 'events' => [\Illuminate\Events\Dispatcher::class, \Illuminate\Contracts\Events\Dispatcher::class], 'files' => [\Illuminate\Filesystem\Filesystem::class], .... ) }
public function __call($method, $parameters) { return $this->connection()->$method(...$parameters); }
##Eloquent ORM
User::find(1)
父類別是不存在這個方法的,它會透過
public static function __callStatic($method, $parameters) { return (new static)->$method(...$parameters); }
User::get()
public function __call($method, $parameters) { if (in_array($method, ['increment', 'decrement'])) { return $this->$method(...$parameters); } return $this->newQuery()->$method(...$parameters); }
new Builder()
而告終,public function newEloquentBuilder($query) { return new Builder($query); }
最後我們到了 Illuminate \Database\Eloquent\Builder 文件下,這個類別涵蓋了ORM的基本操作,例如find , findOrFail 等等。如果你在程式碼用到了get方法,抱歉,這裡沒有,它依舊會透過__call 方法將你的請求轉發到 Illuminate\Database\Query\Builder 類別中
$this->query->{$method}(...$parameters);
以上是Laravel原始碼解析之model(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!