ThinkPHP6.0 門面


通過以下三步了解學習:

  1. 釋義
  2. 自己定義
  3. 系統內置

  1. Facade,即門面設計模式,為容器的類提供了一種靜態的調用方式;

    1. 相比較傳統的靜態方法調用,帶了更好的課測試和擴展性;
    2. 可以為任何的非靜態類庫定一個 Facade 類;
    3. 系統已經為大部分核心類庫定義了Facade;
    4. 所以我們可以通過Facade來訪問這些系統類;
    5. 也可以為我們自己的應用類庫添加靜態代理;
    6. 系統給內置的常用類庫定義了Facade類庫;
  2. 自己定義

    1. 假如我們定義了一個 app\common\Test 類,里面有一個hello動態方法:

      namespace app\common;
      class Test
      {
          public function hello($name)
          {
              return 'hello,' . $name;
          }
      }
      
    2. 我們使用之前的方法調用,具體如下

      $test = new \app\common\Test;
      echo $test->hello('thinkphp');
      // 輸出 hello,thinkphp
      
    3. 我們給這個類定義一個靜態代理類 app\facade\Test,具體如下:

      namespace app\facade;
      use think\Facade;
      
      // 這個類名不一定要和Test類一致,但通常為了便於管理,建議保持名稱統一
      // 只要這個類庫繼承think\Facade;
      // 就可以使用靜態方式調用動態類 app\common\Test的動態方法;
      class Test extends Facade
      {
          protected static function getFacadeClass()
          {
            	return 'app\common\Test';
          }
      }
      
    4. 例如上面調用的代碼就可以改成如下:

      // 無需進行實例化 直接以靜態方法方式調用hello
      echo \app\facade\Test::hello('thinkphp');
      
      // 或者
      use app\facade\Test;
      Test::hello('thinkphp');
      
    5. 說的直白一點,Facade功能可以讓類無需實例化而直接進行靜態方式調用。

  3. 系統內置

    1. 系統給常用類庫定義了Facade類庫,具體如下:

      (動態)類庫 Facade類
      think\App think\facade\App
      think\Cache think\facade\Cache
      think\Config think\facade\Config
      think\Cookie think\facade\Cookie
      think\Db think\facade\Db
      think\Env think\facade\Env
      think\Event think\facade\Event
      think\Filesystem think\facade\Filesystem
      think\Lang think\facade\Lang
      think\Log think\facade\Log
      think\Middleware think\facade\Middleware
      think\Request think\facade\Request
      think\Response think\facade\Response
      think\Route think\facade\Route
      think\Session think\facade\Session
      think\Validate think\facade\Validate
      think\View think\facade\View
    2. 無需進行實例化就可以很方便的進行方法調用:

      namespace app\index\controller;
      use think\facade\Cache;
      class Index
      {
          public function index()
          {
            Cache::set('name','value');
      			echo Cache::get('name');
          }
      }
      
    3. 在進行依賴注入的時候,請不要使用 Facade 類作為類型約束,而使用原來的動態類。

    4. 事實上,依賴注入和使用 Facade 的效果大多數情況下是一樣的,都是從容器中獲取對象實例。

    5. 以下兩種的作用一樣,但是引用的類庫卻不一樣

      // 依賴注入
      namespace app\index\controller;
      use think\Request;
      class Index
      {
      		public function index(Request $request)
          {
              echo $request->controller();
          }
      }
      
      // 門面模式
      namespace app\index\controller;
      use think\facade\Request;
      class Index
      {
          public function index()
          {
              echo Request::controller();
          }
      }
      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM