TableManager.php 1.7 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\Memory;
  12. use RuntimeException;
  13. use Swoole\Table;
  14. class TableManager
  15. {
  16. /**
  17. * A container that use to store atomic.
  18. */
  19. private static array $container = [];
  20. /**
  21. * You should initialize a Table with the identifier before use it.
  22. */
  23. public static function initialize(string $identifier, int $size, float $conflictProportion = 0.2): Table
  24. {
  25. static::$container[$identifier] = new Table($size, $conflictProportion);
  26. return static::$container[$identifier];
  27. }
  28. /**
  29. * Get an initialized Table from container by the identifier.
  30. *
  31. * @throws RuntimeException when the Table with the identifier has not initialization
  32. */
  33. public static function get(string $identifier): Table
  34. {
  35. if (! isset(static::$container[$identifier])) {
  36. throw new RuntimeException('The Table has not initialization yet.');
  37. }
  38. return static::$container[$identifier];
  39. }
  40. /**
  41. * determine if the initialized Table is existed in container by the identifier ?
  42. */
  43. public static function has(string $identifier): bool
  44. {
  45. return isset(static::$container[$identifier]);
  46. }
  47. /**
  48. * Remove the Table by the identifier from container after used,
  49. * otherwise will occur memory leaks.
  50. */
  51. public static function clear(string $identifier): void
  52. {
  53. unset(static::$container[$identifier]);
  54. }
  55. }