Facade

7/8/2021

# Description:

Trong Laravel, facade được sử dụng phổ biến, xem config/app.php.

Thông qua facade:

  • Dễ dàng tiếp cận các service của laravel mà không cần resolved các service này từ Service Container.
  • Bản chất facade không phải là class với các static method.
  • Laravel sử dụng magic method __callStatic để chuyển qua lời gọi method bình thường.
  • Thực chất, các facade được register trong Service Container sẽ được facade resolved và sử dụng.

# Make Facade:

Tạo facade Config trong Nin để tìm hiểu hoạt động của facade:

  • Config:

    Config đã được register ở DI Container và có thể sử dụng thông quan resolved instance Config,

    use Nin\Libs\Config\Contract;
    
    class Config extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return Contract::class;
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
  • Facade:

    //  Nin\Libs\Facades\Facade
    
    public static function __callStatic(string $method, $args)
    {
        $instance = static::getFacadeInstance();
    
        if (!$instance) {
            throw new \Exception('A facade root has not been set.');
        }
    
        return $instance->$method(...$args);
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    __callStatic là 1 magic method giúp override method khi gọi hàm static.

    use Nin\Libs\Facades\Config;
    
    Config::get("foo");
    
    // __callStatic("get", ["foo"])
    
    1
    2
    3
    4
    5

    Resolved facade intance:

    protected static function resolveFacadeInstance($instance)
    {
        if (is_object($instance)) {
            return $instance;
        }
    
        /**
         * Get from facade resolved instance.
         */
        if (isset(static::$resolvedInstance[$instance])) {
            return static::$resolvedInstance[$instance];
        }
    
        /**
         * Get from application container
         */
        if (static::$app) {
            return static::$resolvedInstance[$instance] = static::$app->make($instance);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

Packagist: https://packagist.org/packages/nin/nin (opens new window)