在thinkphp中实现facade的方法
主要的思想是利用call_user_func_array()和容器结合使用的。
核心代码,理解都在注释中:
<?php //reqeuestFacade.php namespace facade{ class Request extends Facade{ public function getFacadeName(){ return 'request'; } } } ?> <?php //facade.php namespace facade{ class Facade{ public static function createFacade(){ $class = static::class; //在这个获取的$class其实是facade\reqeust //在这里利用static::得到getFacadeName,返回真正的request的变量名 $facadeClass = static::getFacadeName(); if ($facadeClass) { $class = $facadeClass; } elseif (isset(self::$bind[$class])) { $class = self::$bind[$class]; } //echo $class; 利用容器去获取reqeust,而不是facade\reqeust return \Container::get($class); } public static function __callStatic($method, $params) { return call_user_func_array([static::createFacade(), $method], $params); } } } ?>
下面测试代码
reqeust.php
<?php class Request{ public $name = 'Real Request'; public function sayName(){ echo $this->name; } } ?>
test.php
<?php use facade\Request; include "Container.php"; include "Facade.php"; include "RequestFacade.php"; include "Request.php"; Request::sayName(); ?>
以上就是在thinkphp中实现facade的方法的详细内容