ThinkPHP6.0快速开发手册(案例版) / 门面 / 外观模式(Facade)

门面 / 外观模式(Facade)

PHP设计模式中的有一个外观模式, 这里叫门面模式, 可以将一些常用的方法套一个静态马甲, 使用静态的方式, 来统一调用接口


为了方便开发者, 框架已将将最常用的许多系统方法, 提前通过门面技术做了封装

假如我们定义了一个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类库,包括:


(动态)类库Facade类
think\Appthink\facade\App
think\Cachethink\facade\Cache
think\Configthink\facade\Config
think\Cookiethink\facade\Cookie
think\Dbthink\facade\Db
think\Envthink\facade\Env
think\Eventthink\facade\Event
think\Filesystemthink\facade\Filesystem
think\Langthink\facade\Lang
think\Logthink\facade\Log
think\Middlewarethink\facade\Middleware
think\Requestthink\facade\Request
think\Responsethink\facade\Response
think\Routethink\facade\Route
think\Sessionthink\facade\Session
think\Validatethink\facade\Validate
think\Viewthink\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();
    }
}

在实际开发中, 推荐优先使用: 依赖注入