[PHP]Symfony or Laravel 在 console 中结合 Workerman
在web框架的console中,命令不再是直接指定入口文件,如以往 php test.php start,而是类似 php app/console do 的形式。
workerman 对命令的解析是 parseCommand 方法,里面主要是处理 $argv 全局变量。
那么我们只需要在自己的逻辑中对其重新赋值,满足 $argv[1] 是动作 start | stop | restart | … 即可,那么剩余workerman参数就是 $argv[2],依次类推。
Symfony command:
namespace AppBundle\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Workerman\Connection\TcpConnection; use Workerman\Worker; /** * @author farwish * * Class DataWorkerCommand * @package AppBundle\Command */ class DataWorkerCommand extends BaseCommand { public function configure() { $this->setName('xc:data:worker') ->setDescription('启动服务') ->addArgument( 'subcommands', InputArgument::IS_ARRAY, '可选多个参数' ) ; } /** * app/console xc:data:worker start d * app/console xc:data:worker stop * app/console xc:data:worker status * app/console xc:data:worker restart * * @param InputInterface $input * @param OutputInterface $output */ public function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); // redefine arguments global $argv; $argv[1] = $argv[2]; $argv[2] = isset($argv[3]) ? "-{$argv[3]}" : ''; unset($argv[3]); // worker $worker = new Worker("websocket://0.0.0.0:9000"); $worker->count = 4; $worker->onMessage = function ($connection, $data) { /* @var TcpConnection $connection */ $connection->send('hello'); }; Worker::runAll(); } }
Laravel command:
namespace App\Console\Commands; use Illuminate\Console\Command; use Workerman\Connection\TcpConnection; use Workerman\Worker; class SendEmail extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'send:msg {action}'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * php artisan send:msg start */ public function handle() { global $argv; $argv[1] = $argv[3]; $argv[2] = isset($argv[4]) ? "-{$argv[4]}" : ''; $mailWorker = new Worker('websocket://0.0.0.0:9000'); $mailWorker->count = 4; $mailWorker->name = 'MailWorker'; $mailWorker->onMessage = function ($connection, $data) { $connection->send('hello'); }; Worker::runAll(); } }
Thats all.