search
HomePHP FrameworkLaravelDetailed interpretation of Laravel Facade

The following is a detailed explanation of Laravel Facade from the Laravel tutorial column. Hope it helps those in need!

Detailed interpretation of Laravel Facade

Hello everyone, today’s content is about the implementation principle of Laravel’s Facade mechanism.

Simple use of Facade

Use of database:

$users = DB::connection('foo')->select(...);

IOC container

As we all know, the IOC container is the most important part of the Laravel framework. It provides two functions, IOC and containers.

  • IOC (Inversion of Control), also called inversion of control. To put it bluntly, it is to control the generation of objects so that developers do not need to care about how the objects are generated, but only need to care about their use.
  • The object instance generated through the IOC mechanism needs a storage location for continued use, which is its container function.

This time I am not going to explain the specific implementation of the IOC container. There will be articles explaining it in detail later. Regarding IOC containers, readers only need to remember two points:

  1. Generate object instances according to configuration;
  2. Save object instances for easy access at any time;

Simplified Facade class

<?php
namespace facades;

abstract class Facade
{
    protected static $app;

    /** 
     * Set the application instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public static function setFacadeApplication($app)
    {   
        static::$app = $app;
    } 

    /** 
     * Get the registered name of the component.
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    protected static function getFacadeAccessor()
    {
        throw new RuntimeException(&#39;Facade does not implement getFacadeAccessor method.&#39;);
    }

    /** 
     * Get the root object behind the facade.
     *
     * @return mixed
     */
    public static function getFacadeRoot()
    {   
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    } 

    /**
     * Resolve the facade root instance from the container.
     *
     * @param  string|object  $name
     * @return mixed
     */
    protected static function resolveFacadeInstance($name)
    {
        return static::$app->instances[$name];
    }

    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException(&#39;A facade root has not been set.&#39;);
        }   

        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);
        } 
    }
}

Code description:

  1. $app stores an IOC container instance, which is passed through setFacadeApplication( ) The
  2. set by this static method implements the __callStatic magic method
  3. The getFacadeAccessor() method requires subclasses to inherit and returns a string identifier. Through this identifier, the IOC container can return The object of the class it is bound to (framework initialization or binding at other times)
  4. Call specific methods through $instance

Create your own Facade:

TEST1 The specific logic:

<?php
class Test1{
	public function hello()
	{
		print("hello world");
	}}

Facade of the TEST1 class:

<?php
namespace facades;/**
 * Class Test1
 * @package facades
 *
 * @method static setOverRecommendInfo [设置播放完毕时的回调函数]
 * @method static setHandlerPlayer [明确指定下一首时的执行类]
 */class Test1Facade extends Facade{
    protected static function getFacadeAccessor()
    {   
        return &#39;test1&#39;;
    }   }

Usage:

use facades\Test1Facade;Test1Facade::hello();  // 这是 Facade 调用

Explanation:

  1. facades\Test1Facade calls the static method hello (), since this method is not defined, __callStatic will be called;
  2. In __callStatic, the corresponding instance is first obtained, that is, return static::$app->instances[$name ];. The $name is the test1$app in
  3. facades\Test1
  4. , which is the IOC container, and the instantiation process of the class is handed over to it to handle.

The above is the detailed content of Detailed interpretation of Laravel Facade. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
How to Build a RESTful API with Advanced Features in Laravel?How to Build a RESTful API with Advanced Features in Laravel?Mar 11, 2025 pm 04:13 PM

This article guides building robust Laravel RESTful APIs. It covers project setup, resource management, database interactions, serialization, authentication, authorization, testing, and crucial security best practices. Addressing scalability chall

Laravel framework installation latest methodLaravel framework installation latest methodMar 06, 2025 pm 01:59 PM

This article provides a comprehensive guide to installing the latest Laravel framework using Composer. It details prerequisites, step-by-step instructions, troubleshooting common installation issues (PHP version, extensions, permissions), and minimu

laravel-admin menu managementlaravel-admin menu managementMar 06, 2025 pm 02:02 PM

This article guides Laravel-Admin users on menu management. It covers menu customization, best practices for large menus (categorization, modularization, search), and dynamic menu generation based on user roles and permissions using Laravel's author

How to Implement OAuth2 Authentication and Authorization in Laravel?How to Implement OAuth2 Authentication and Authorization in Laravel?Mar 12, 2025 pm 05:56 PM

This article details implementing OAuth 2.0 authentication and authorization in Laravel. It covers using packages like league/oauth2-server or provider-specific solutions, emphasizing database setup, client registration, authorization server configu

What version of laravel is the bestWhat version of laravel is the bestMar 06, 2025 pm 01:58 PM

This article guides Laravel developers in choosing the right version. It emphasizes the importance of selecting the latest Long Term Support (LTS) release for stability and security, while acknowledging that newer versions offer advanced features.

How can I create and use custom validation rules in Laravel?How can I create and use custom validation rules in Laravel?Mar 17, 2025 pm 02:38 PM

The article discusses creating and using custom validation rules in Laravel, offering steps to define and implement them. It highlights benefits like reusability and specificity, and provides methods to extend Laravel's validation system.

What Are the Best Practices for Using Laravel in a Cloud-Native Environment?What Are the Best Practices for Using Laravel in a Cloud-Native Environment?Mar 14, 2025 pm 01:44 PM

The article discusses best practices for deploying Laravel in cloud-native environments, focusing on scalability, reliability, and security. Key issues include containerization, microservices, stateless design, and optimization strategies.

How do I use Laravel's components to create reusable UI elements?How do I use Laravel's components to create reusable UI elements?Mar 17, 2025 pm 02:47 PM

The article discusses creating and customizing reusable UI elements in Laravel using components, offering best practices for organization and suggesting enhancing packages.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)