Home > PHP Framework > ThinkPHP > body text

How to implement facade in thinkphp

Release: 2020-03-31 09:21:07
forward
2742 people have browsed it

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


?>
Copy after login

The following test code

reqeust.php

<?php

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

    public  function sayName(){
        echo $this->name;
    }

}

?>
Copy after login

test.php

<?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!

Related labels:
source:segmentfault.com
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!