Workerman是純PHP開發的開源高效能的非同步PHP socket框架。 ThinkPHP是一個快速、相容且簡單的輕量級國產PHP開發框架,本文就來為大家介紹一下Thinkphp5.1裡使用workerman的方法。

之前一直用swoole,最近研究workerman,於是composer安裝
composer require workerman/workerman
在Thinkphp控制器裡面寫一段測試程式碼
<?php
namespace app\workerman\controller;
use think\Controller;
use Workerman\Worker;
class Index extends Controller
{
public function index()
{
// 创建一个Worker监听2345端口,使用http协议通讯
$http_worker = new Worker("http://0.0.0.0:2345");
// 启动4个进程对外提供服务
$http_worker->count = 4;
// 接收到浏览器发送的数据时回复hello world给浏览器
$http_worker->onMessage = function($connection, $data)
{
// 向浏览器发送hello world
$connection->send('hello world');
};
// 运行worker
Worker::runAll();
}
}命令列執行:php index.php workerman/index。以為大功告成,但是卻報下面的提示:
很明顯,workerman不能直接運行文件,看官方文檔是使用
php index .php start
php index.php stop
php index.php restart
#這樣的格式執行。於是修改index.php檔綁定路由
// [ 应用入口文件 ]
namespace think;
// 加载基础文件
require __DIR__ . '/../thinkphp/base.php';
// 支持事先使用静态方法设置Request对象和Config对象
// 执行应用并响应
Container::get('app')->bind("workerman/index")->run()->send();直接運行php index.php start,汗,居然提示說找不到start這個模型。特麼tp5把start當作路由解析了。那怎麼辦,workerman的需要用start的方式執行,tp5卻要把這個參數解析成模型啊。
後查閱資料發現,Thinkphp5.1本身就整合了workerman了。可以使用thinkphp5的方式安裝workerman,這樣就可以使用thinkphp的運作方式運作了。
執行指令改成:
php think worker
後續發現Thinkphp5.1整合的workerman封裝的有點麻煩,不好用,而且如果你想用PHPSocketIO之類的workerman服務用整合的方式很麻煩。
workerman把第一個參數當作操作服務的命令,那我把它改成用第二個參數當操作命令列不行?
果然就是這麼做的。找出workerman外掛裡面的parseCommand()函數。這個鬼函數就是取得那個操作指令的,把:
argv[1]改成argv[2],argv[2]改成argv[2]改成argv[2]改成argv[3 ]
protected static function parseCommand()
{
if (static::$_OS !== OS_TYPE_LINUX) {
return;
}
global $argv;
// Check argv;
$start_file = $argv[0];
$available_commands = array(
'start',
'stop',
'restart',
'reload',
'status',
'connections',
);
$usage = "Usage: php yourfile <command>
[mode]\nCommands: \nstart\t\tStart worker in DEBUG mode.\n\t\tUse mode -d to start in DAEMON mode.\nstop\t\tStop worker.\n\t\tUse mode -g to stop gracefully.\nrestart\t\tRestart workers.\n\t\tUse mode -d to start in DAEMON mode.\n\t\tUse mode -g to stop gracefully.\nreload\t\tReload codes.\n\t\tUse mode -g to reload gracefully.\nstatus\t\tGet worker status.\n\t\tUse mode -d to show live status.\nconnections\tGet worker connections.\n";
if (!isset($argv[2]) || !in_array($argv[2], $available_commands)) {
if (isset($argv[2])) {
static::safeEcho('Unknown command: ' . $argv[2] . "\n");
}
exit($usage);
}
// Get command.
$command = trim($argv[2]);
$command2 = isset($argv[3]) ? $argv[3] : '';執行指令改成
php server.php index start
(第一個參數用於Thinkphp解析路由,第二個參數用於workerman解析操作服務指令)
更多workerman知識請關注PHP中文網workerman架構教學欄位。
以上是Thinkphp5.1裡使用workerman的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!