On this page
发送信息api
需要创建的文件
php
// 聊天控制器
php think make:controller api/v1/Chat
// 聊天验证器
php think make:validate ChatValidate
控制器层:application\api\v1\Chat.php
php
<?php
namespace app\api\controller\v1;
use think\Controller;
use think\Request;
use app\common\controller\BaseController;
use GatewayWorker\Lib\Gateway;
use think\facade\Cache;
use app\common\validate\ChatValidate;
class Chat extends BaseController
{
// 初始化registerAddress
public function __construct(){
Gateway::$registerAddress = config('gateway_worker.registerAddress');
}
// 发送信息
public function send(Request $request){
// 1. 验证数据是否合法
(new ChatValidate)->goCheck('send');
// 2. 组织数据
$data = $this->resdata($request);
$to_id = $request->to_id;
// 3. 验证对方用户是否在线
if (Gateway::isUidOnline($to_id)) {
// 直接发送
Gateway::sendToUid($to_id,json_encode($data));
// 写入数据库
// 返回发送成功
return self::showResCodeWithOutData('ok');
}
// 不在线,写入消息队列
// 获取之前消息
$Cache = Cache::get('userchat_'.$to_id);
if (!$Cache || !is_array($Cache)) $Cache = [];
$Cache[] = $data;
// 写入数据库
// 写入消息队列(含id)
Cache::set('userchat_'.$to_id,$Cache);
return self::showResCodeWithOutData('ok',200);
}
// 组织数据
public function resdata($request){
return [
'to_id'=>$request->to_id,
'from_id'=>$request->userId,
'from_userpic'=>$request->from_userpic,
'type'=>$request->type,
'data'=>$request->data,
'time'=>time()
];
}
}
路由层:route\route.php
php
// socket 部分
Route::group('api/:v1/',function(){
// 发送信息
Route::post('chat/send','api/:v1.Chat/send');
})->middleware(['ApiUserAuth','ApiUserBindPhone','ApiUserStatus']);
验证器层:application\common\validate\ChatValidate
php
protected $rule = [
'to_id'=>'require|isUserExist',
'from_userpic'=>'require',
'type'=>'require',
'data'=>'require',
];
protected $scene = [
'send'=>['to_id','from_userpic','type','data']
];