通過以下三步了解學習:
- 釋義
- 自己定義
- 系統內置
-
Facade,即門面設計模式,為容器的類提供了一種靜態的呼叫方式;
- 相比較傳統的靜態方法呼叫,帶了更好的課測驗和擴展性;
- 可以為任何的非靜態類別庫定一個 Facade 類;
- 系統已經為大部分核心類別庫定義了Facade;
- 所以我們可以通過Facade來訪問這些系統類;
- 也可以為我們自己的應用類別庫添加靜態代理;
- 系統給內置的常用類別庫定義了Facade類別庫;
-
自己定義
-
假如我們定義了一個 app\common\Test 類,里面有一個hello動態方法:
namespace app\common; class Test { public function hello($name) { return 'hello,' . $name; } } -
我們使用之前的方法呼叫,具體如下
$test = new \app\common\Test; echo $test->hello('thinkphp'); // 輸出 hello,thinkphp -
我們給這個類定義一個靜態代理類 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'; } } -
例如上面呼叫的代碼就可以改成如下:
// 無需進行實體化 直接以靜態方法方式呼叫hello echo \app\facade\Test::hello('thinkphp'); // 或者 use app\facade\Test; Test::hello('thinkphp'); -
說的直白一點,Facade功能可以讓類無需實體化而直接進行靜態方式呼叫,
-
-
系統內置
-
系統給常用類別庫定義了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 -
無需進行實體化就可以很方便的進行方法呼叫:
namespace app\index\controller; use think\facade\Cache; class Index { public function index() { Cache::set('name','value'); echo Cache::get('name'); } } -
在進行依賴注入的時候,請不要使用 Facade 類作為型別約束,而使用原來的動態類,
-
事實上,依賴注入和使用 Facade 的效果大多數情況下是一樣的,都是從容器中獲取物件實體,
-
以下兩種的作用一樣,但是參考的類別庫卻不一樣
// 依賴注入 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(); } }
-
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/36399.html
標籤:PHP
