TP5.1静态代理

1.静态代理

【1】被代理类,app\common\Test

<?php
namespace app\common;

class Test
{
    public function hello($name)
    {
        return "hello ".$name;
    }
}

【2】代理类,app\facade\Test

<?php

#当前类是代理类,代理的类名app\common\test
namespace app\facade;

class Test extends \think\Facade{
    protected static function getFacadeClass()
    {
        return 'app\common\Test';//代理的类名
    }
}

【3】调用静态代理 app\index\controller\Demo2

<?php
namespace app\index\controller;


class Demo2
{
    public function index($name = 'ThinkPHP')
    {
        //传统访问方式
        // $test = new \app\common\Test();
        // return $test->hello($name);
        
        /**
         * 如果想静态调用一个动态方法,需要给当前类绑定一个静态代理的类
         */
        return \app\facade\Test::hello('孔雀翎');
    }
}

2.动态绑定静态代理

【1】被代理类省略

【2】代理类,app\facade\Test

<?php

#当前类是代理类,代理的类名app\common\test
namespace app\facade;

class Test extends \think\Facade{
  
}

【3】调用静态代理 app\index\controller\Demo2

<?php
namespace app\index\controller;

class Demo2
{
    public function index($name = 'ThinkPHP')
    {
        //动态绑定代理类与被代理类,前者为代理类,后者为被代理类
        //如果没有在静态代理类中显示指定要绑定的类名,就要动态显示要绑定一下
        //\think\Facade::bind()
        \think\Facade::bind('app\facade\Test', 'app\common\Test');
        return \app\facade\Test::hello('孔雀翎');
    }
}

3.请求对象的实例

namespace app\index\controller;
use think\facade\Request;//导入请求对象的静态代理
/**
 * 正常情况下,控制器不依赖于父类Controller.php
 * 但是通常情况推荐继承父类,可以很方便的使用父类中封装好的一些方法和属性
 * Controller.php没有静态代理
 * 控制器中的输出,字符串全部用return返回,不要用echo
 * 如果输出复杂类型,我们可以使用dump()函数
 * 默认输出的格式为html,可以指定为其他格式:json
 */
class Demo3 extends \think\Controller
{
    public function test()
    {
        //创建一个请求对象Request的静态代理
        dump(Request::get());
        //http://localhost:8090/tpjiuzhu30/public/index.php/index/demo3/test?name=Perter&sex=1
        /**
         * array(2) {
         *   ["name"] => string(6) "Perter"
         *   ["sex"] => string(3) "男"
         *   }
         */


         /**
          * 请求对象的调用方式
          * 传统的new Request
          * 静态代理 think\facade\Request
          * 依赖注入 Request $request
          * 父类Controller的属性$request: $this->request  
          */
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章