ファサード・外観モード(ファサード)


開発者を容易にするために、フレームワークはファサード テクノロジを通じて、最も一般的に使用されるシステム メソッドの多くを事前にカプセル化しています。

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');

コア ファサード クラス ライブラリ

システムは、次のような一般的に使用される組み込みクラス ライブラリのファサード クラス ライブラリを定義します。


(動的) クラス ライブラリファサード クラス#think\Appthink\Cachethink\Configthink\Cookiethink\Db think\Envthink \イベントthink\ファイルシステム #think\Langthink\Logthink\ミドルウェアthink\Requestthink\Response think\Routethink \Sessionthink\Validatethink\View
think\facade\App
think\facade\Cache
think\facade\ Config
think\facade\Cookie
think\facade\Db
think\facade\Env
think\facade\Event
think\facade\ファイルシステム
think\facade\Lang
think\facade\Log
think\facade\Middleware
think\facade\Request
think\facade\Response
think\facade\Route
think\facade\Session
think\facade\Validate
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();
    }
}

と同じ効果があります。実際の開発では、次の使用をお勧めします。 依存関係の挿入



#