Home Backend Development PHP Tutorial What are containers and facades? A brief analysis of containers and facades in thinkphp5.1

What are containers and facades? A brief analysis of containers and facades in thinkphp5.1

Aug 10, 2018 am 10:57 AM

This article brings you what is a container (Container) and a facade (Facade)? The brief analysis of containers and facades in thinkphp5.1 has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

p5.1 introduced two new classes, container (Container) and facade (Facade)

The official document has given the definition:

Container (Container) ) to achieve unified management of classes and ensure the uniqueness of object instances.

Facade provides a static calling interface for classes in the container (Container). Compared with traditional static method calling, it brings better testability and scalability. You can Any non-static class library defines a facade class.

Deep into the source code, let’s take a look at how it is implemented:

// 在框架目录下的base.php文件

// 注册核心类到容器
Container::getInstance()->bind([
    'app'                   => App::class,
    'build'                 => Build::class,
    'cache'                 => Cache::class,
    'config'                => Config::class,
    ...
]);

// 注册核心类的静态代理
Facade::bind([
    facade\App::class      => App::class,
    facade\Build::class    => Build::class,
    facade\Cache::class    => Cache::class,
    facade\Config::class   => Config::class,
    ...
]);

// 注册类库别名
Loader::addClassAlias([
    'App'      => facade\App::class,
    'Build'    => facade\Build::class,
    'Cache'    => facade\Cache::class,
    'Config'   => facade\Config::class,
    ...
]);
Copy after login

Container implementation:

Here, the framework has helped us bind common system classes to the container When using it later, you only need to call the helper function app() to perform class parsing calls in the container. The bound class identifier will be automatically and quickly instantiated.

// 实例化缓存类

app('cache'); 
// app('cache', ['file']); 参数化调用

// 相当于执行了
Container::get('cache');

// 查看源码,Container调用的其实是make方法,在该方法里调用反射等实现类的实例化,过程如下:
Copy after login
public function make($abstract, $vars = [], $newInstance = false)
{
    if (true === $vars) {
        // 总是创建新的实例化对象
        $newInstance = true;
        $vars        = [];
    }

    if (isset($this->instances[$abstract]) && !$newInstance) {
        $object = $this->instances[$abstract];
    } else {
        if (isset($this->bind[$abstract])) {
            $concrete = $this->bind[$abstract];
       // 闭包实现
            if ($concrete instanceof \Closure) {
                $object = $this->invokeFunction($concrete, $vars);
            } else {
                $object = $this->make($concrete, $vars, $newInstance);
            }
        } else {
       // 反射实现
            $object = $this->invokeClass($abstract, $vars);
        }

        if (!$newInstance) {
            $this->instances[$abstract] = $object;
        }
    }

    return $object;
}
Copy after login
/**
 * 调用反射执行类的实例化 支持依赖注入
 * @access public
 * @param  string    $class 类名
 * @param  array     $vars  变量
 * @return mixed
 */
public function invokeClass($class, $vars = [])
{
    $reflect     = new \ReflectionClass($class);
    $constructor = $reflect->getConstructor();

    if ($constructor) {
        $args = $this->bindParams($constructor, $vars);
    } else {
        $args = [];
    }

    return $reflect->newInstanceArgs($args);
}
Copy after login
/**
 * 执行函数或者闭包方法 支持参数调用
 * @access public
 * @param  string|array|\Closure $function 函数或者闭包
 * @param  array                 $vars     变量
 * @return mixed
 */
public function invokeFunction($function, $vars = [])
{
    $reflect = new \ReflectionFunction($function);
    $args    = $this->bindParams($reflect, $vars);

    return $reflect->invokeArgs($args);
}
Copy after login

In short, the instantiation of classes is implemented inside the container through reflection classes or closures.

Facade implementation:

Let’s analyze it with an example:

facade\Config::get('app_debug');
Copy after login

Let’s analyze its implementation:

// thinkphp\library\facade\Config 类
Copy after login
namespace think\facade;

use think\Facade;

class Config extends Facade
{
}
Copy after login

// From the source code There is no method in Config itself. It inherits the method of Facade, but Facade does not get this static method
// At this time, the system automatically triggers the magic method: __callStatic(), and Facade rewrites this method:

public static function __callStatic($method, $params)
{
    return call_user_func_array([static::createFacade(), $method], $params);
}
Copy after login

// It can be seen that the last call is the user-defined function: call_user_func_array([instance, method], parameter). In order to obtain the Config instance, Facade defines a method to obtain the object:

/**
 * 创建Facade实例
 * @static
 * @access protected
 * @param  string    $class          类名或标识
 * @param  array     $args           变量
 * @param  bool      $newInstance    是否每次创建新的实例
 * @return object
 */
protected static function createFacade($class = '', $args = [], $newInstance = false)
{
    $class       = $class ?: static::class;
    $facadeClass = static::getFacadeClass();

    if ($facadeClass) {
        $class = $facadeClass;
    } elseif (isset(self::$bind[$class])) {
        $class = self::$bind[$class];
    }

    if (static::$alwaysNewInstance) {
        $newInstance = true;
    }

    return Container::getInstance()->make($class, $args, $newInstance);
}
Copy after login

// The object is instantiated internally through the container
// Because the think\Config class has been bound to the config identifier in base.php

Container::getInstance()->bind([
  'config'  => Config::class
])

// 在 createFacade 方法中,获取类的名称:$class = $class ?: static::class; 即得到 config 这个标识
Copy after login
// 在容器的make方法中,根据config标识,找到绑定的 think\Config 类,并调用其动态方法 get。

facade\Config::get('app_debug'); 

// 最后调用的是:

(new think\Config())->get('app_debug');
Copy after login

In short, The facade is implemented through PHP's magic method __callStatic, and then cooperates with the container to realize static calling of dynamic classes.

Related recommendations:

thinkphp template How to determine whether mobile WeChat payment or WeChat scan code payment

PHP wants to achieve page jump How does the function work? (Function label example)

The above is the detailed content of What are containers and facades? A brief analysis of containers and facades in thinkphp5.1. For more information, please follow other related articles on the PHP Chinese website!

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months 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)

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,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

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.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

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�...

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...

See all articles