Рубрики
Uncategorized

Реализация фасадов PHP

Автор оригинала: David Wong.

Пример

php
 
class RealRoute{
 
    public function get(){
        Echo'Get me';
    }    
}

class Facade{
    public static $resolvedInstance;
    public static $app;
    public static function __callStatic($method,$args){
        $instance = static::getFacadeRoot();
        if(!$instance){
            throw new RuntimeException('A facade root has not been set.');
        }
        return $instance->$method(...$args);
    }
    // Get the Facade root object
    public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }
    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];
    }    
}
class Router extends Facade{
    protected static function getFacadeAccessor(){
        return 'router';
    }
}

class Container{

    public $binding;
    
    public function bind($name,$obj){
        $this->binding[$name] = $obj;
    }
    
    public function make($name,$args=[]){
        call_user_func_array($name, $args);
    }
}
// Step 1: Add the service container first
/*$container = new Facade;
$container->bind('router',function(){
    return new RealRoute;
})*/

Router::$app['router']=new RealRoute;
// Step 2: Create a Category Name
class_alias('Router','Route');
// Step 3: Call class methods through the facade
Route::get();

Другой

PHP Волшебный метод _call и _call Статический метод Простое понимание функций call_user_func и call_user_func_array Class_alias — Создайте псевдоним для класса

Оригинал: “https://developpaper.com/implementation-of-php-facades/”