Gateway/Worker模型 數(shù)據(jù)庫使用示例
提示
推薦使用webman的GatewayWorker插件,對業(yè)務(wù)目錄、數(shù)據(jù)庫、redis等支持更完善。
安裝
具體安裝使用參見 Workerman手冊 Workerman/MySQL
使用示例
項目/Events.php
<?php
use \GatewayWorker\Lib\Gateway;
require_once '/your/path/of/mysql-master/src/Connection.php';
/**
* 數(shù)據(jù)庫示例,假設(shè)有個your_db_name庫,里面有個user表
*/
class Events
{
/**
* 新建一個類的靜態(tài)成員,用來保存數(shù)據(jù)庫實例
*/
public static $db = null;
/**
* 進程啟動后初始化數(shù)據(jù)庫連接
*/
public static function onWorkerStart($worker)
{
self::$db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
}
/**
* 有消息時觸發(fā)該方法,根據(jù)發(fā)來的命令打印2個用戶信息
* @param int $client_id 發(fā)消息的client_id
* @param mixed $message 消息
* @return void
*/
public static function onMessage($client_id, $message)
{
// 發(fā)來的消息
$commend = trim($message);
if($commend !== 'get_user_list')
{
Gateway::sendToClient($client_id, "unknown commend\n");
return;
}
// 使用數(shù)據(jù)庫實例
self::$db->select('*')->from('users')->where('uid>3')->offset(5)->limit(2)->query();
// 打印結(jié)果
return Gateway::sendToClient($client_id, var_export($ret, true));
}
}