有时我们需要在代码中使用预先定义好的常量,
例如当前时间戳,由于代码封装了许多层,每次都用Carbon::now()获取当前时间有可能时间会一致。
这里有一个很简单的小技巧
话不多说上代码

新建存放变量的类

  1. namespace App\Light\Box;
  2. class BoxContainer
  3. {
  4. //全局时间戳
  5. const NOW = 'NOW';
  6. //保存变量键值对
  7. public $mountData = [];
  8. /**
  9. * 挂载变量
  10. * @param $key //键
  11. * @param $value //值
  12. */
  13. public function mount($key, $value)
  14. {
  15. //没有赋值,则赋值
  16. if (!isset($this->mount[$key])) {
  17. $this->mountData[$key] = $value;
  18. }
  19. }
  20. /**
  21. * 获取指定变量
  22. * @param $key
  23. * @return mixed|string
  24. */
  25. public function get($key)
  26. {
  27. return isset($this->mountData[$key]) ? $this->mountData[$key] : '';
  28. }
  29. }

创建门面类

  1. namespace App\Light\Box;
  2. use Illuminate\Support\Facades\Facade;
  3. /**
  4. * 让IDE有语法提示
  5. * @method static \App\Light\Box\BoxContainer mount($key, $value, $force = false)
  6. * @method static \App\Light\Box\BoxContainer unmount($key)
  7. * @method static \App\Light\Box\BoxContainer get($key)
  8. */
  9. class Box extends Facade
  10. {
  11. protected static function getFacadeAccessor()
  12. {
  13. return 'BoxContainer';
  14. }
  15. }

创建服务提供者

  1. namespace App\Light\Box;
  2. use Illuminate\Support\ServiceProvider;
  3. use Illuminate\Support\Carbon;
  4. class BoxServiceProvider extends ServiceProvider
  5. {
  6. public function register()
  7. {
  8. //绑定单例
  9. $this->app->singleton('BoxContainer', function () {
  10. return new BoxContainer();
  11. });
  12. //初始化变量
  13. Box::mount(BoxContainer::NOW,Carbon::now());
  14. }
  15. }

注册服务提供者

将以下代码加入config/app.php中

  1. //注册变量容器服务提供者
  2. App\Light\Box\BoxServiceProvider::class,

现在可以在项目中肆意使用了

  1. dump(Box::get(BoxContainer::NOW));