Container.php 1.3 KB

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