Home > PHP Framework > Laravel > body text

Laravel source code analysis model (code)

不言
Release: 2018-09-30 15:35:21
forward
4408 people have browsed it

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';
}
Copy after login

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();
Copy after login
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()
Copy after login
. 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],
            ....
        )
}
Copy after login
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);
}
Copy after login
, 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)
Copy after login

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);
}
Copy after login

. In the same way,

User::get()
Copy after login

is called through

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

. This method finally ends with

new Builder()

. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">public function newEloquentBuilder($query) {     return new Builder($query); }</pre><div class="contentsignin">Copy after login</div></div>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);
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template