Table of Contents
前言
select()方法的2种使用
1. 链式调用:
2. 静态调用:
分解
Laravel 中的 Facades
总结
Home Backend Development PHP Tutorial DB Facade 中的 select 方法分解

DB Facade 中的 select 方法分解

Jun 23, 2016 pm 01:02 PM

前言

Laravel 框架中的查询构造器相当的强大,可能是我的基础太差。当我看到 DB Facade 中的 select 方法时一时不能理解,于是就有了这篇文章。

select()方法的2种使用

1. 链式调用:

$users = DB::table('users')->select('uname, realname')->get(); 
Copy after login

通过 Laravel Debugbar 上面这句代码执行的SQL是:

select `uname`, `realname` from `users` 
Copy after login

2. 静态调用:

$sql = "select uname, realname from users";$users = DB::select($sql); 
Copy after login

这种方式,执行的SQL语句跟链式调用执行语句是一样的。

分解

据其文档描述table()会针对指定的数据表返回一个查询构造器实例,追踪到 DB Facade 类中

--文件位置 framework/src/Illuminate/Support/Facades/DB.php namespace Illuminate\Support\Facades;/*** @see \Illuminate\Database\DatabaseManager* @see \Illuminate\Database\Connection*/class DB extends Facade{    /**     * Get the registered name of the component.     *     * @return string     */    protected static function getFacadeAccessor()    {        return 'db';    }} 
Copy after login

这个文件中根本没有table()这个静态方法,但是这个类继承了 Facade 这个类

Laravel 中的 Facades

Laravel Facade 是一种为容器内部服务提供类型静态接口的类。据其文档描述,Facades 是可触及容器服务底层实现方式的代理。使用 facade 类的好处是让开发者使用服务是更加便捷。

Facade 类中包含一个名为 $app的私有属性,其值为服务容器的引用。

__callStatic魔术方法用于处理实际并不存在的静态方法的调用。因为 Facade 类并未实现该方法。因此,__callStatic 会从容器获取各自的服务,进而调用。

__callStatic 方法具体实现:

--!文件位置 framework/src/Illuminate/Support/Facades/Facade.php /**+ Handle dynamic, static calls to the object.*+ @param  string  $method+ @param  array   $args+ @return mixed*/public static function __callStatic($method, $args){    $instance = static::getFacadeRoot();    if (! $instance) {        throw new RuntimeException('A facade root has not been set.');    }    switch (count($args)) {        case 0:            return $instance->$method();        case 1:            return $instance->$method($args[0]);        case 2:            return $instance->$method($args[0], $args[1]);        case 3:            return $instance->$method($args[0], $args[1], $args[2]);        case 4:            return $instance->$method($args[0], $args[1], $args[2], $args[3]);        default:            return call_user_func_array([$instance, $method], $args);    }} 
Copy after login

通过 $instance = static::getFacadeRoot()来得到调用该方法的所属实例

public static function getFacadeRoot(){    return static::resolveFacadeInstance(static::getFacadeAccessor());} 
Copy after login

在 DB Facade中 已实现 getFacadeAccessor()该方法 return 'db'。

protected static function resolveFacadeInstance($name){  if (is_object($name)) {      return $name;  }  if (isset(static::$resolvedInstance[$name])) {      return static::$resolvedInstance[$name];  }  return static::$resolvedInstance[$name] = static::$app[$name];} 
Copy after login

通过 __callStatic() 及 static::后期静态绑定。实现了这个伪静态的调用。这也就明白了为什么可以通过静态方法调用DB::select()。

我们再回到第一种调用方式:

--文件位置 #Illuminate\Database\Querypublic function select($colums = ['*']){    $this->columns = is_array($columns) ? $columns : func_get_args();    return $this;} 
Copy after login

通过源码可以看出 select 是个可变参数函数,默认接收一个数组。

总结

通过对 select 的分解,我们也可知道其他 Facades 中方法的运作原理。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles