PoolFactory.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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\Pool\SimplePool;
  12. use Psr\Container\ContainerInterface;
  13. use function Hyperf\Support\make;
  14. class PoolFactory
  15. {
  16. /**
  17. * @var Pool[]
  18. */
  19. protected array $pools = [];
  20. protected array $configs = [];
  21. public function __construct(protected ContainerInterface $container)
  22. {
  23. }
  24. public function addConfig(Config $config)
  25. {
  26. $this->configs[$config->getName()] = $config;
  27. return $this;
  28. }
  29. public function get(string $name, callable $callback, array $option = []): Pool
  30. {
  31. if (! $this->hasConfig($name)) {
  32. $config = new Config($name, $callback, $option);
  33. $this->addConfig($config);
  34. }
  35. $config = $this->getConfig($name);
  36. if (! isset($this->pools[$name])) {
  37. $this->pools[$name] = make(Pool::class, [
  38. 'callback' => $config->getCallback(),
  39. 'option' => $config->getOption(),
  40. ]);
  41. }
  42. return $this->pools[$name];
  43. }
  44. public function getPoolNames(): array
  45. {
  46. return array_keys($this->pools);
  47. }
  48. protected function hasConfig(string $name): bool
  49. {
  50. return isset($this->configs[$name]);
  51. }
  52. protected function getConfig(string $name): Config
  53. {
  54. return $this->configs[$name];
  55. }
  56. }