외관/외관 모드(외관)
개발자의 작업을 용이하게 하기 위해 프레임워크는 가장 일반적으로 사용되는 많은 시스템 메소드를 Facade 기술을 통해 미리 캡슐화했습니다.
hello 동적 메소드가 있는 appcommonTest 클래스를 정의한다고 가정해 보겠습니다.
<?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');
이 클래스에 대해 정적 프록시 클래스 appfacadeTest를 정의합니다(클래스 이름은 임의적이지만 이를 통일된 상태로 유지하면 유지 관리가 용이해집니다).
<?php namespace app\facade; use think\Facade; class Test extends Facade { protected static function getFacadeClass() { return 'app\common\Test'; } }
이 클래스 라이브러리가 thinkFacade를 상속하는 한 정적 메서드를 사용하여 동적 클래스 appcommonTest의 동적 메서드를 호출할 수 있습니다. 예를 들어 위 코드는 다음과 같이 변경할 수 있습니다.
// 无需进行实例化 直接以静态方法方式调用hello echo \app\facade\Test::hello('thinkphp');
Core Facade 클래스 라이브러리
시스템은 내장된 공통 클래스 라이브러리를 제공합니다. Facade 클래스 라이브러리는 다음을 포함하여 정의됩니다.
(동적) 클래스 라이브러리 | Facade 클래스 |
---|---|
thinkApp | thinkfacadeApp |
thinkCache | thinkfacadeCache |
thinkConfig | thinkfacadeConfig |
thinkCookie | thinkfacadeCookie |
thinkDb | thinkfacadeDb |
thinkEnv | thinkfacadeEnv |
thinkEvent | thinkfacadeEvent |
thinkFilesystem | thinkfacadeFilesystem |
thinkLang | thinkfacadeLang |
thinkLog | thinkfacadeLog |
thinkMiddleware | thinkfacadeMiddleware |
thinkRequest | thinkfacadeRequest |
thinkResponse | thinkfacadeResponse |
thinkRoute | thinkfacadeRoute |
thinkSession | thinkfacadeSession |
thinkValidate | thinkfacadeValidate |
thinkView | thinkfacadeView |
따라서 인스턴스화 없이 쉽게 메서드 호출을 할 수 있습니다. 예:
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(); } }
과 동일한 효과를 갖습니다. 실제 개발에서는 다음을 사용하는 것이 좋습니다. 종속성 주입