Facade wrapper class - solves the problem of long namespace calls in the view

巴扎黑
Release: 2016-11-09 11:28:23
Original
889 people have browsed it

Sometimes the definition in the template requires writing a long full path class name. Here is a simple alias calling code to avoid this problem. The disadvantage is that the IDE code prompt function is gone


 * // 初始化
 * 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);
    }
}
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!