StaticInstance.php 792 B

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Support\Traits;
  12. use Hyperf\Context\Context;
  13. trait StaticInstance
  14. {
  15. public static function instance(array $params = [], bool $refresh = false, string $suffix = ''): static
  16. {
  17. $key = get_called_class() . $suffix;
  18. $instance = null;
  19. if (Context::has($key)) {
  20. $instance = Context::get($key);
  21. }
  22. if ($refresh || ! $instance instanceof static) {
  23. $instance = new static(...$params);
  24. Context::set($key, $instance);
  25. }
  26. return $instance;
  27. }
  28. }