用戶訂閱的流程分為三步
1.根據(jù)用戶發(fā)送的json數(shù)據(jù)的type判斷消息類型。
2.如果是登錄用戶,就將用戶的信息存儲到redis中。
3.返回給用戶一個登錄成功的狀態(tài)。
4.通知所有用戶“xxx”進入了直播。
在app目錄下,一共有兩個目錄,一個是controllers,負責(zé)數(shù)據(jù)的收發(fā),一個是services,負責(zé)具體邏輯的處理。
├── app
│ ├── controllers
│ └── services
在services目錄下新建push文件夾,所有通知推送相關(guān)的服務(wù)全部寫在該文件夾中。
第一、新建app/services/push/PushObServer.php文件,用來規(guī)定消息通知的接口。
<?php
namespace app\services\push;
interface PushObServer
{
function update();
}
第二、新建一個通知當(dāng)前用戶注冊是否成功的類,app/services/push/PushToSelfRegisterInfo,這個類用來繼承Interface接口,實現(xiàn)其中的方法。
同樣,我們需要創(chuàng)建一個給其他用戶發(fā)消息的類,以便通知其他用戶“xxx進入了房間”。
//注冊結(jié)果通知類
<?php
namespace app\services\push;
use app\services\CommonService;
class PushToSelfRegisterInfo extends PushCommonService implements PushObServer
{
protected $server;
protected $msg;
protected $fds;
public function __construct(\swoole_websocket_server $server,$msg, $fds)
{
$this->server=$server;
$this->msg=$msg;
$this->fds=$fds;
}
public function update()
{
$this->result['msg'] = $this->msg;
$params = json_encode($this->result, JSON_UNESCAPED_UNICODE);
if(!$this->fds){
return false;
}
foreach ($this->fds as $fd) {
$this->server->push($fd, $params);
}
return true;
}
}
//給其他用戶發(fā)消息的類。
<?php
namespace app\services\push;
class PushToAllMessage extends PushCommonService implements PushObServer
{
private $server;
private $msg;
private $fds;
public function __construct(\swoole_websocket_server $server,$data, $fds)
{
$this->server=$server;
$this->result['data']=$data;
$this->fds=$fds;
}
/**
* @inheritDoc
*/
function update()
{
$params = json_encode($this->result, JSON_UNESCAPED_UNICODE);
if(!$this->fds){
return false;
}
foreach ($this->fds as $fd) {
$this->server->push($fd, $params);
}
return true;
}
}
這個類的作用是在用戶注冊成功之后,給用戶自己返回一個注冊成功與否的信息。
第三、新建一個抽象類app/services/push/PushEventGenerator,用于接收新增的消息通知類型。
<?php
namespace app\services\push;
abstract class PushEventGenerator
{
protected $events=[];
public function addPushObServer(PushObServer $obServer){
$this->events[]=$obServer;
}
public function notify(){
foreach($this->events as $event){
$event->update();
}
}
}
PushEventGenerator類中一共有兩個方法,第一個方法是將當(dāng)前所有的通知都存放到$events這個數(shù)組中,第二個方法是執(zhí)行通知的具體方法,取出所有的需要通知的內(nèi)容,執(zhí)行其中的update方法。
OK,接下來我們可以直接在業(yè)務(wù)中,調(diào)用通知方法了。