Home >PHP Framework >ThinkPHP >How to implement facade in thinkphp

How to implement facade in thinkphp

尚
forward
2020-03-31 09:21:072822browse

How to implement facade in thinkphp

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:

<?php
//reqeuestFacade.php
    namespace facade{
        class Request extends Facade{
            public function getFacadeName(){
                return &#39;request&#39;;
            }
        }
    }

?>

<?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);
        }
    }
}


?>

The following test code

reqeust.php

<?php

class Request{
    public $name = &#39;Real Request&#39;;

    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();

?>

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete