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  
          */
    }
}

 

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