发布于 1970-01-01 08:00
  • 1 个回答
    • 这个是另一个package,你说的“自己实现”,其实也对的,这个地方也可以放你自己定义的class

      其实这段代码产生的效果是

      比如

      $this->app->singleton('ReportServices', function () {
          return new \App\Services\ReportServices();
      });

      以后在其他class里我可以用

      app('ReportServices')->xxxxxx();

      去代替

      $services = new \App\Services\ReportServices();
      $services->xxxxxx();

      Providers的存在目的就是在程序启动的时候注册各种东西,比如你要扩展Cache类去使用阿里云ocs

      public function boot()
          {
              //扩展阿里云OCS缓存
              Cache::extend('ocs', function ($app, $config) {
                  $prefix = $app['config']['cache.prefix'];
                  $memcached = new \Memcached;
                  foreach ($config['servers'] as $server) {
                      $memcached->addServer(
                          $server['host'], $server['port'], $server['weight']
                      );
                      if (ini_get('memcached.use_sasl')) {
                          $user = $server['authname'];
                          $pass = $server['authpass'];
      
                          $memcached->setOption(\Memcached::OPT_COMPRESSION, false);
                          $memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
                          $memcached->setSaslAuthData($user, $pass);
                      }
                  }
                  $store = new \Illuminate\Cache\MemcachedStore($memcached, $prefix);
      
                  return new \Illuminate\Cache\Repository($store);
              });
      }

      比如你要扩展表单验证类

      public function boot()
      {
          //扩展表单验证
              Validator::extend('greater_than', function ($attribute, $value, $parameters)     
              {
                  $other = Request::input($parameters[0]);
      
                  return isset($other) && intval($value) > intval($other);
              });
      }
      2022-12-01 15:46 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有