門面 / 外觀模式(Facade)


為了方便開發者, 框架已將最常用的許多系統方法, 提前透過門面技術做了封裝

#假如我們定義了一個app\common\Test類,裡面有一個hello動態方法。

<?php
namespace app\common;

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

呼叫hello方法的程式碼應該類似於:

$test = new \app\common\Test;
// 输出 hello,thinkphp
echo $test->hello('thinkphp');

我們為這個類別定義一個靜態代理類別app\facade\Test(類別名稱任意, 但保持統一會便於維護)。

<?php
namespace app\facade;

use think\Facade;

class Test extends Facade
{
    protected static function getFacadeClass()
    {
    	return 'app\common\Test';
    }
}

只要這個類別庫繼承think\Facade,就可以用靜態方式呼叫動態類別app\common\Test的動態方法,例如上面的程式碼就可以改成:

// 无需进行实例化 直接以静态方法方式调用hello
echo \app\facade\Test::hello('thinkphp');

核心Facade類別庫

系統為內建的常用類別庫定義了Facade類別庫,包括:


## think\facade\Eventthink\Filesystemthink\facade\Filesystemthink\Langthink\facade\Langthink\Logthink\facade\Logthink\Middlewarethink\facade\Middlewarethink\Requestthink\facade\Requestthink\Response think\facade\Responsethink\Route
(動態)類別庫Facade類別
#think\Appthink\facade\App
think\Cachethink\facade\Cache
think\Configthink\facade\ Config
think\Cookiethink\facade\Cookie
think\Db#think\ facade\Db
think\Envthink\facade\Env
think\Event

think\facade\Route

think \Session

think\facade\Session

think\Validate

think\facade\Validate


#think\View

think\facade\View

###################所以你不需要進行實例化就可以很方便的進行方法調用,例如:###
use think\facade\Cache;

Cache::set('name','value');
echo Cache::get('name');
###在進行依賴注入的時候,請不要使用Facade類作為類型約束,而是建議使用原來的動態類,以下是錯誤的用法:###
<?php
namespace app\index\controller;

use think\facade\App;

class Index
{
    public function index(App $app)
    {
    }
}
## #應當使用下面的方式:###
<?php
namespace app\index\controller;

use think\App;

class Index
{
    public function index(App $app)
    {
    }
}
###事實上,依賴注入和使用Facade代理的效果大多數情況下是一樣的,都是從容器中獲取物件實例。例如:###
<?php
namespace app\index\controller;

use think\Request;

class Index
{
    public function index(Request $request)
    {
        echo $request->controller();
    }
}
###和下面的作用是一樣的###
<?php
namespace app\index\controller;

use think\facade\Request;

class Index
{
    public function index()
    {
        echo Request::controller();
    }
}
###在實際開發中, 推薦優先使用: 依賴注入################ ## ###