The main idea is to use call_user_func_array() in conjunction with the container.
The core code and understanding are all in the comments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?php
namespace facade{
class Request extends Facade{
public function getFacadeName(){
return 'request';
}
}
}
?>
<?php
namespace facade{
class Facade{
public static function createFacade(){
$class = static :: class ;
$facadeClass = static ::getFacadeName();
if ( $facadeClass ) {
$class = $facadeClass ;
} elseif (isset(self:: $bind [ $class ])) {
$class = self:: $bind [ $class ];
}
利用容器去获取reqeust,而不是facade\reqeust
return \Container::get( $class );
}
public static function __callStatic( $method , $params )
{
return call_user_func_array([ static ::createFacade(), $method ], $params );
}
}
}
?>
|
Copy after login
The following test code
reqeust.php
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
class Request{
public $name = 'Real Request';
public function sayName(){
echo $this ->name;
}
}
?>
|
Copy after login
test.php
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
use facade\Request;
include "Container.php" ;
include "Facade.php" ;
include "RequestFacade.php" ;
include "Request.php" ;
Request::sayName();
?>
|
Copy after login
Recommended tutorial: thinkphp tutorial
The above is the detailed content of How to implement facade in thinkphp. For more information, please follow other related articles on the PHP Chinese website!