ThinkPHP6.0 门面

ThinkPHP6.0 门面


通过以下三步了解学习:

  1. 释义
  2. 自己定义
  3. 系统内置

  1. Facade,即门面设计模式,为容器的类提供了一种静态的调用方式;

    1. 相比较传统的静态方法调用,带了更好的课测试和扩展性;
    2. 可以为任何的非静态类库定一个 Facade 类;
    3. 系统已经为大部分核心类库定义了Facade;
    4. 所以我们可以通过Facade来访问这些系统类;
    5. 也可以为我们自己的应用类库添加静态代理;
    6. 系统给内置的常用类库定义了Facade类库;
  2. 自己定义

    1. 假如我们定义了一个 app\common\Test 类,里面有一个hello动态方法:

      namespace app\common;
      class Test
      {
          public function hello($name)
          {
              return 'hello,' . $name;
          }
      }
      
    2. 我们使用之前的方法调用,具体如下

      $test = new \app\common\Test;
      echo $test->hello('thinkphp');
      // 输出 hello,thinkphp
      
    3. 我们给这个类定义一个静态代理类 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';
          }
      }
      
    4. 例如上面调用的代码就可以改成如下:

      // 无需进行实例化 直接以静态方法方式调用hello
      echo \app\facade\Test::hello('thinkphp');
      
      // 或者
      use app\facade\Test;
      Test::hello('thinkphp');
      
    5. 说的直白一点,Facade功能可以让类无需实例化而直接进行静态方式调用。

  3. 系统内置

    1. 系统给常用类库定义了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
    2. 无需进行实例化就可以很方便的进行方法调用:

      扫描二维码关注公众号,回复: 11248400 查看本文章
      namespace app\index\controller;
      use think\facade\Cache;
      class Index
      {
          public function index()
          {
            Cache::set('name','value');
      			echo Cache::get('name');
          }
      }
      
    3. 在进行依赖注入的时候,请不要使用 Facade 类作为类型约束,而使用原来的动态类。

    4. 事实上,依赖注入和使用 Facade 的效果大多数情况下是一样的,都是从容器中获取对象实例。

    5. 以下两种的作用一样,但是引用的类库却不一样

      // 依赖注入
      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();
          }
      }
      

猜你喜欢

转载自www.cnblogs.com/laowenBlog/p/12937476.html