WithContainer.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace think\swoole\concerns;
  3. use think\App;
  4. use think\console\Output;
  5. use think\exception\Handle;
  6. use Throwable;
  7. trait WithContainer
  8. {
  9. /**
  10. * @var App
  11. */
  12. protected $container;
  13. /**
  14. * Manager constructor.
  15. * @param App $container
  16. */
  17. public function __construct(App $container)
  18. {
  19. $this->container = $container;
  20. }
  21. protected function getContainer()
  22. {
  23. return $this->container;
  24. }
  25. /**
  26. * 获取配置
  27. * @param string $name
  28. * @param null $default
  29. * @return mixed
  30. */
  31. public function getConfig(string $name, $default = null)
  32. {
  33. return $this->container->config->get("swoole.{$name}", $default);
  34. }
  35. /**
  36. * 触发事件
  37. * @param string $event
  38. * @param null $params
  39. */
  40. protected function triggerEvent(string $event, $params = null): void
  41. {
  42. $this->container->event->trigger("swoole.{$event}", $params);
  43. }
  44. /**
  45. * 监听事件
  46. * @param string $event
  47. * @param $listener
  48. * @param bool $first
  49. */
  50. public function onEvent(string $event, $listener, bool $first = false): void
  51. {
  52. $this->container->event->listen("swoole.{$event}", $listener, $first);
  53. }
  54. /**
  55. * Log server error.
  56. *
  57. * @param Throwable $e
  58. */
  59. public function logServerError(Throwable $e)
  60. {
  61. /** @var Handle $handle */
  62. $handle = $this->container->make(Handle::class);
  63. $handle->renderForConsole(new Output(), $e);
  64. $handle->report($e);
  65. }
  66. }