Home Backend Development PHP Tutorial Laravel5学习四:Facade的运行机制

Laravel5学习四:Facade的运行机制

Jun 23, 2016 pm 01:32 PM

什么是Facades

官方文档如是说:

Facades 提供一个 静态接口 给在应用程序的 服务容器 中可以取用的类。Laravel 附带许多 facades,甚至你可能已经在不知情的状况下使用过它们!Laravel 的「facades」作为在 IoC 容器里面的基础类的静态代理,提供的语法有简洁、易表达的优点,同时维持比传统的静态方法更高的可测试性和弹性。

说实话,这段话读起来真不像人类的语言,我准备来拆解一下。
首先, Facades 是一个类,是一个什么类呢?它是基础类的一个静态代理。
其次, Facades 是可以直接从IOC容器中拿到的,对应到laravel5就是说,可以直接使用,它已经存在于app这个容器中。
最后, 为什么要有 Facades 这个东东?首先优点是:它提供的语法更简洁,易表达。这个其实不是主要原因,个人觉得最主要的原因是:便于可测试性与降低耦合性(代理模式的优点)

用例子来说明

PS:本部分内容参考自网络:原文地址

我们知道$app 在laravel中是一个特殊的全局变量,它在最初启动的时候就是ioc容器的对象实例。
于是如果我们要取从ioc容器中取一个实例出来,是这样写的:

$value = $app->make('cache')->get('key');
Copy after login

由于$app implements PHP的 ArrayAccess interface,所以可以更简化点,写成:

$value = $app['cache']->get('key');
Copy after login

你甚至可以用函数的方式写成这样:

$value = app('cache')->get('key');
Copy after login

这个时候Facace跳出来说,我可以写成这样:

$value = Cache::get('key');
Copy after login
运行机制分析
  • Facades 的命名空间
    相信只要玩过laravel的人,都会见过当遇到 Facades 的时候,导入命名空间,只需要用 use XXX 即可。不用把完整的的命名空间写出来。这是为什么?
    正常的类的命名空间,应该这样写:
  • use Illuminate\Support\Facades\Cache;
    Copy after login

    Facades 只需要这样写:

    use Cache;
    Copy after login

    为什么能够这样?我看了一些它的运行过程,解析如下:

    这幅图,中的关键点是:AliasLoader中注册的自动加载方法,它使用了我们在app.php配置中的 aliases 数组,从而通过这个别名,可以找到对应的真实类存在的文件,然后完成对象的实例化。

  • 如何构建自己的 Facades
    PS:还是以 Cache 为例子
  • 首先需要构建的就是Cache这个类本身,实现它的功能。这里对应的文件是:
    Illuminate\Cache\CacheManager (备注:由于Cache有多种实现,因此通过管理者来获取想要的Cache实现方案。)

    当Cache这个类,写好之后,我们要将它绑定到一个服务提供者里边去,这里的服务提供者位置是:
    Illuminate\Cache\CacheServiceProvider ,绑定部分代码是:

    public function register() {    $this->app->singleton('cache', function ($app) {        return new CacheManager($app);    });    ......    }
    Copy after login

    这里需要注意的是,绑定时,为什么要使用’cache’ 这个字符串,后面会讲到。当服务提供者写好后,需要在 app.php 的 providers 的数组中配置服务提供者,此处代码如下:

    'providers' => [    /* * Laravel Framework Service Providers... */    Illuminate\Foundation\Providers\ArtisanServiceProvider::class, Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, ...... ]
    Copy after login

    完成以下步骤后,就可以构建 Facades 类了,Cache 的 Facades 的位置在 Illuminate\Support\Facades\Cache 。

    <?phpnamespace Illuminate\Support\Facades;/** * @see \Illuminate\Cache\CacheManager * @see \Illuminate\Cache\Repository */class Cache extends Facade {    /** * Get the registered name of the component. * * @return string */    protected static function getFacadeAccessor() {        return 'cache';    }}
    Copy after login

    所有的 Facades 类都需要继承自 Facades ,并实现 getFacadeAccessor 方法。它的工作是定义要从容器解析什么。这也就是说,如果我们绑定的时候,写的是 cache ,那么这里也需要返回 cache ,要不然解析的时候,就会找不到。大家可以试试改成其它名字。
    最后一步,需要配置 app.php 中的 aliases 数组,这涉及到 Facades 的自动加载。就是最开始画的那幅图。

    'aliases' => [    'App'       => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Bus' => Illuminate\Support\Facades\Bus::class, 'Cache' => Illuminate\Support\Facades\Cache::class, ...... ]
    Copy after login
    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 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)

    How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

    Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

    The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

    How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

    How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

    How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

    How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

    How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

    Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

    See all articles