ICO容器和Facade机制示意

/**
 * Facade基类
 */
class Facade{
    protected static $container;

    /**
     * @param mixed $container
     */
    public static function setContainer($container)
    {
        self::$container = $container;
    }

    public static function __callStatic($name, $args)
    {
        $accessorKey = static::getFacadeAccessor();
        $accessor = self::$container->{$accessorKey};
        if (!method_exists($accessor,$name)){
            throw new \BadMethodCallException("调用了不存在的方法".static::class."::".$name);
        }
        return call_user_func_array([$accessor,$name],$args);
    }

    public static function getFacadeAccessor(){
        throw new \RuntimeException("门面".static::class."没有实现 getFacadeAccessor 静态方法");
    }
}
/**
 * Facade实际代理
 */
class Printer extends Facade{
    public static function getFacadeAccessor(){
        return 'printer';
    }
}
/**
 * 服务具体实现类
 */
class PrinterService{

    public function __construct()
    {
        "sasdasd";
    }

    public function write($string)
    {
        echo $string;
    }
}
容器示例
class Container
{
    protected $service = [];

    public function __get($name)
    {
        if (!isset($this->service[$name])){
            throw new \UnexpectedValueException("未注册的服务");
        }
        $isFactory = is_object($this->service[$name]) && method_exists($this->service[$name], '__invoke');
        return $isFactory ? $this->service[$name] ($this) : $this->service[$name] ;
    }

    public function __set($name,$value)
    {
        $this->service[$name] = $value;
    }
}
//实例化容器
$container = new Container();
// 注册服务
$container->printer = function (){
    return new PrinterService();
};
// Facade 设置容器
Facade::setContainer($container);
// 代理调用
Printer::write("打印机服务演示");

评论

captcha