Container.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\Utils\Traits;
  12. trait Container
  13. {
  14. /**
  15. * @var array
  16. */
  17. protected static $container = [];
  18. /**
  19. * Add a value to container by identifier.
  20. * @param mixed $value
  21. */
  22. public static function set(string $id, $value)
  23. {
  24. static::$container[$id] = $value;
  25. }
  26. /**
  27. * Finds an entry of the container by its identifier and returns it,
  28. * Retunrs $default when does not exists in the container.
  29. * @param null|mixed $default
  30. */
  31. public static function get(string $id, $default = null)
  32. {
  33. return static::$container[$id] ?? $default;
  34. }
  35. /**
  36. * Returns true if the container can return an entry for the given identifier.
  37. * Returns false otherwise.
  38. */
  39. public static function has(string $id): bool
  40. {
  41. return isset(static::$container[$id]);
  42. }
  43. /**
  44. * Returns the container.
  45. */
  46. public static function list(): array
  47. {
  48. return static::$container;
  49. }
  50. /**
  51. * Clear the container.
  52. */
  53. public static function clear(): void
  54. {
  55. static::$container = [];
  56. }
  57. }