自定义命令

自定义命令需要实现EasySwoole\Console\ModuleInterface接口的3个方法

创建控制器

新建文件App\Console\TestConsole.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Tioncico
  5. * Date: 2019/3/11 0011
  6. * Time: 11:41
  7. */
  8. namespace App\console;
  9. use EasySwoole\Console\ModuleInterface;
  10. use EasySwoole\Socket\Bean\Caller;
  11. use EasySwoole\Socket\Bean\Response;
  12. class TestConsole implements ModuleInterface
  13. {
  14. /**
  15. * 命令执行
  16. * exec
  17. * @param Caller $caller
  18. * @param Response $response
  19. * @author Tioncico
  20. * Time: 11:47
  21. */
  22. public function exec(Caller $caller, Response $response)
  23. {
  24. $args = $caller->getArgs();
  25. $actionName = array_shift($args);
  26. $caller->setArgs($args);
  27. switch ($actionName) {
  28. case 'echo':
  29. $this->echo($caller, $response);
  30. break;
  31. default :
  32. $this->help($caller, $response);
  33. }
  34. // TODO: Implement exec() method.
  35. }
  36. /**
  37. * 该命令的帮助
  38. * help
  39. * @param Caller $caller
  40. * @param Response $response
  41. * @author Tioncico
  42. * Time: 11:48
  43. */
  44. public function help(Caller $caller, Response $response)
  45. {
  46. // TODO: Implement help() method.
  47. $help = <<<HELP
  48. 测试的自定义控制器
  49. 用法: 命令 [命令参数]
  50. test echo [string] | 输出字符串,测试方法
  51. HELP;
  52. $response->setMessage($help);
  53. // TODO: Implement help() method.
  54. }
  55. /**
  56. * 返回控制器名称
  57. * moduleName
  58. * @return string
  59. * @author Tioncico
  60. * Time: 11:48
  61. */
  62. public function moduleName(): string
  63. {
  64. return 'Test';
  65. // TODO: Implement moduleName() method.
  66. }
  67. /**
  68. * 输出方法
  69. * echo
  70. * @param $arg
  71. * @author Tioncico
  72. * Time: 11:50
  73. */
  74. private function echo(Caller $caller, Response $response)
  75. {
  76. $msg = array_shift($caller->getArgs());
  77. $response->setMessage($msg);
  78. }
  79. }

注册控制器

EasySwooleEvent.phpinitialize事件中注册该命令控制器:

  1. <?php
  2. \EasySwoole\Console\ConsoleModuleContainer ::getInstance()->set(new TestConsole());

调用控制器

登陆控制台之后,输入test echo 仙士可即可出现结果:

  1. [root@localhost tioncico_demo]# php easyswoole console
  2. connect to tcp://127.0.0.1:9500 success
  3. Welcome to EasySwoole Console
  4. auth fail,please auth, auth {USER} {PASSWORD}
  5. auth root 123456
  6. auth success
  7. help
  8. Welcome to EasySwoole remote console
  9. Usage: command [action] [...arg]
  10. For help: help [command] [...arg]
  11. Current command list:
  12. test
  13. help
  14. auth
  15. server
  16. log
  17. test echo 仙士可
  18. 仙士可