PHP-Facades的实现

54次阅读

共计 1193 个字符,预计需要花费 3 分钟才能阅读完成。

示例

<?php
 
class RealRoute{public function get(){echo '获得我';}    
}

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);
    }
    // 获取 Facade 根对象
    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);
    }
}
//step1: 先加入服务容器
/*$container = new Facade;
$container->bind('router',function(){return new RealRoute;})*/

Router::$app['router']=new RealRoute;
//step2: 创建类别名
class_alias('Router','Route');
//step3: 通过门面调用类方法
Route::get();
 

其他

PHP 魔术方法 __call 与 __callStatic 方法
简单理解 call_user_func 和 call_user_func_array 两个函数
class_alias– 为一个类创建别名

正文完
 0