Facade 包装类 -- 解决视图里面长长的命名空间调用问题
程序员文章站
2022-04-11 19:00:07
...
有时候模版里面定义需要写很长的全路径类名,此处提供一个 简易的别名调用代码来规避此问题,缺点就是IDE 代码提示功能就没有了
* // 初始化 * ZGFacade::setZGFacade('form', 'Aert_Form'); * ZGFacade::setZGFacade('esClient', '\Elasticsearch\Client'); * * // 使用demo * $form = ZGFacade::newInstance('form', 'frm2', 'delete'); * dump($form); * * echo ZGFacade::server('form', 'REQUEST_METHOD'); * echo ZGFacade::get('form', 'a'); * * $dsn = Config::get('esken.dsn'); * $esClient = ZGFacade::newInstance('esClient', $dsn); * dump($esClient); * * @author vb2005xu@qq.com */ final class ZGFacade { private static $map = [ 'form'=> 'Aert_Form' ]; public static function setZGFacade($alias, $class) { self::$map[ $alias ] = $class; } private static function __facade__($facade, $method, $arguments=[]) { if ( is_object($facade) ) { // 调用 对象方法 return call_user_func_array( [$facade, $method], $arguments ); } else if (is_string($facade)) { if ( empty(self::$map[$facade]) ) { throw new Exception("未定义 'facade': {$facade} "); } // 调用 静态方法 if ( 'newInstance' == $method ) { $class = new ReflectionClass( self::$map[$facade] ); return $class->newInstanceArgs( $arguments ); } $class = self::$map[$facade]; return call_user_func_array( [$class, $method], $arguments ); } throw new Exception("无效 'facade' 调用!"); } public function __call($method, $arguments) { $facade = array_shift($arguments); return self::__facade__($facade, $method, $arguments); } public static function __callStatic($method, $arguments) { $facade = array_shift($arguments); return self::__facade__($facade, $method, $arguments); } }
上一篇: java之集合类温故而知新