BaseRabbitMQ.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php declare(strict_types=1);
  2. namespace mikemadisonweb\rabbitmq\components;
  3. use PhpAmqpLib\Channel\AMQPChannel;
  4. use PhpAmqpLib\Connection\AbstractConnection;
  5. abstract class BaseRabbitMQ
  6. {
  7. protected $conn;
  8. protected $autoDeclare;
  9. protected $ch;
  10. /**
  11. * @var $logger Logger
  12. */
  13. protected $logger;
  14. /**
  15. * @var $routing Routing
  16. */
  17. protected $routing;
  18. /**
  19. * @param AbstractConnection $conn
  20. * @param Routing $routing
  21. * @param Logger $logger
  22. * @param bool $autoDeclare
  23. */
  24. public function __construct(AbstractConnection $conn, Routing $routing, Logger $logger, bool $autoDeclare)
  25. {
  26. $this->conn = $conn;
  27. $this->routing = $routing;
  28. $this->logger = $logger;
  29. $this->autoDeclare = $autoDeclare;
  30. if ($conn->connectOnConstruct()) {
  31. $this->getChannel();
  32. }
  33. }
  34. public function __destruct()
  35. {
  36. $this->close();
  37. }
  38. public function close()
  39. {
  40. if ($this->ch) {
  41. try {
  42. $this->ch->close();
  43. } catch (\Exception $e) {
  44. // ignore on shutdown
  45. }
  46. }
  47. if ($this->conn && $this->conn->isConnected()) {
  48. try {
  49. $this->conn->close();
  50. } catch (\Exception $e) {
  51. // ignore on shutdown
  52. }
  53. }
  54. }
  55. public function renew()
  56. {
  57. if (!$this->conn->isConnected()) {
  58. return;
  59. }
  60. $this->conn->reconnect();
  61. }
  62. /**
  63. * @return AMQPChannel
  64. */
  65. public function getChannel()
  66. {
  67. if (empty($this->ch) || null === $this->ch->getChannelId()) {
  68. $this->ch = $this->conn->channel();
  69. }
  70. return $this->ch;
  71. }
  72. }