Home  >  Article  >  PHP Framework  >  Laravel source code analysis model (code)

Laravel source code analysis model (code)

不言
不言forward
2018-09-30 15:35:224409browse

The content of this article is about the model (code) of Laravel source code analysis. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface

I wish the apes a happy National Day in advance. Eat well, drink well and play well. I will watch you on TV.

According to the single responsibility development principle, during the development process of laravel, each table should establish a model for external services and calls. Similar to this

namespace App\Models;
    
use Illuminate\Database\Eloquent\Model;
    
class User extends Model
{
    protected $table = 'users';
}

Parsing

Laravel’s data operations are divided into two types

  • DB facade

  • Eloquent ORM

In addition to their own characteristics, basic data operations are completed through Illuminate\Database\Query\Builder calling methods to complete the entire SQL. You can also use the Builder class as the base class for the entire SQL operation. This class covers the following operation methods (partially shown)

method
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', $ where = 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)
It can be seen that there are many methods on the Chinese laravel website or official documents. There is no reflection, so even if you want to be proficient in a framework, you can't do it without looking at its source code. This file is under vendor/laravel/framework/src/Illuminate/Database/Query in your project directory. You can check it yourself.

DB facade

Normally you may write an operation like this

DB::table('user')->get();
This operation first points to the file through laravel's facade, but it is not in app.php. Instead, it is loaded directly through the kernel, and it is registered at

Illuminate\Foundation\Application -> registerCoreContainerAliases()
. The facade directly calls the Illuminate\Database\DatabaseManager class.

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],
            ....
        )
}
Illuminate\Database\DatabaseManager There is not much code in it, most of it handles database connections. When you use DB::table(), it will be forwarded through

public function __call($method, $parameters)
{
    return $this->connection()->$method(...$parameters);
}
, the call is Illuminate\Database\Connection, the user processes the table() method, and then points to Illuminate\Database\ through the table() method Query class, we have talked about this class at the beginning, so I won’t go into details here. Then comes the splicing of various SQLs->Execute SQL->End the battle

Laravel source code analysis model (code)##Eloquent ORM

Eloquent ORM is similar to the DB facade. First, each Eloquent ORM needs to inherit the parent class Illuminate\Database\Eloquent\Model

You will probably write like this

User::find(1)

This method does not exist in the parent class. It will forward the request call through
public static function __callStatic($method, $parameters)
{
    return (new static)->$method(...$parameters);
}

. In the same way,

User::get()

is called through

public function __call($method, $parameters)
{
    if (in_array($method, ['increment', 'decrement'])) {
        return $this->$method(...$parameters);
    }
        
    return $this->newQuery()->$method(...$parameters);
}

. This method finally ends with

new Builder()

. <pre class="brush:php;toolbar:false">public function newEloquentBuilder($query) {     return new Builder($query); }</pre>Finally we arrive at Illuminate \Database\Eloquent\Builder file, this class covers the basic operations of ORM, such as find, findOrFail, etc. If you use the get method in your code, sorry, not here, it will still forward your request to the Illuminate\Database\Query\Builder class through the __call method

$this->query->{$method}(...$parameters);

The entire data operation is completed. .

Laravel source code analysis model (code)

The above is the detailed content of Laravel source code analysis model (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete