分享几个 Hyperf 常用助手函数

使用 hyperf 已经有一段时间了,下面是一些常用的助手函数,分享一下~~~

  1. <?php
  2. use Hyperf\Contract\StdoutLoggerInterface;
  3. use Hyperf\HttpServer\Contract\ResponseInterface;
  4. use Hyperf\Logger\LoggerFactory;
  5. use Hyperf\Server\ServerFactory;
  6. use Hyperf\Utils\ApplicationContext;
  7. use Psr\Http\Message\ServerRequestInterface;
  8. use Swoole\Websocket\Frame;
  9. use Swoole\WebSocket\Server as WebSocketServer;
  10. /**
  11. * 容器实例
  12. */
  13. if (!function_exists('container')) {
  14. function container()
  15. {
  16. return ApplicationContext::getContainer();
  17. }
  18. }
  19. /**
  20. * redis 客户端实例
  21. */
  22. if (!function_exists('redis')) {
  23. function redis()
  24. {
  25. return container()->get(Redis::class);
  26. }
  27. }
  28. /**
  29. * server 实例 基于 swoole server
  30. */
  31. if (!function_exists('server')) {
  32. function server()
  33. {
  34. return container()->get(ServerFactory::class)->getServer()->getServer();
  35. }
  36. }
  37. /**
  38. * websocket frame 实例
  39. */
  40. if (!function_exists('frame')) {
  41. function frame()
  42. {
  43. return container()->get(Frame::class);
  44. }
  45. }
  46. /**
  47. * websocket 实例
  48. */
  49. if (!function_exists('websocket')) {
  50. function websocket()
  51. {
  52. return container()->get(WebSocketServer::class);
  53. }
  54. }
  55. /**
  56. * 缓存实例 简单的缓存
  57. */
  58. if (!function_exists('cache')) {
  59. function cache()
  60. {
  61. return container()->get(Psr\SimpleCache\CacheInterface::class);
  62. }
  63. }
  64. /**
  65. * 控制台日志
  66. */
  67. if (!function_exists('stdLog')) {
  68. function stdLog()
  69. {
  70. return container()->get(StdoutLoggerInterface::class);
  71. }
  72. }
  73. /**
  74. * 文件日志
  75. */
  76. if (!function_exists('logger')) {
  77. function logger()
  78. {
  79. return container()->get(LoggerFactory::class)->make();
  80. }
  81. }
  82. /**
  83. *
  84. */
  85. if (!function_exists('request')) {
  86. function request()
  87. {
  88. return container()->get(ServerRequestInterface::class);
  89. }
  90. }
  91. /**
  92. *
  93. */
  94. if (!function_exists('response')) {
  95. function response()
  96. {
  97. return container()->get(ResponseInterface::class);
  98. }
  99. }