导航

TP6:自定义Workerman指令

Posted on 2022-05-10 15:38  eastson  阅读(457)  评论(0编辑  收藏  举报

https://www.kancloud.cn/manual/thinkphp6_0/1147857

有时候我们希望使用think的命令行运行workerman,这里做一个介绍,

通过 composer 安装

composer require topthink/think-worker

1:先新建一个指令,参考文档:自定义指令,比如新建命令:

php think make:command Hello hello

2:复制下面的代码到指令里,覆盖原始的configure和execute方法

  protected function configure()
  {
    // 指令配置
    $this->setName('convert')
      ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
      ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
      ->setDescription('the workerman command');
  }

  protected function execute(Input $input, Output $output)
  {
    // 指令输出
    $output->writeln('convert start');

    $action = $input->getArgument('action');
    $mode = $input->getOption('mode');


    // 重新构造命令行参数,以便兼容workerman的命令
    global $argv;

    $argv = [];

    array_unshift($argv, 'think', $action);
    if ($mode == 'd') {
      $argv[] = '-d';
    } else if ($mode == 'g') {
      $argv[] = '-g';
    }

    // 在这里放心的实例化worker,
    // 就像参照workerman文档写一样,
    // 无非在workerman的文档里,代码是新建纯php文件,但在这里,写到了一个方法里.
    $worker_1 = new Worker();
    $worker_2 = new Worker();

    Worker::runAll();
  }

3:运行的时候,使用如下命令:

//临时运行
php think hello start
//后台运行
php think hello start --mode d