我有一个yii2
带有高级模板的项目,我想使用mosquitto broker
. 我已经完成了发布部分并正在工作,现在我想在订阅我的前端应用程序上的主题方面获得一些帮助。我已经尝试过了,但是当我订阅任何主题时,页面似乎停止工作。有什么简单的方法或教程可以使用吗?如果需要更多信息,请询问。
PS:我的想法是:当我在前端打开任何页面时,我会检查消息,将它们保存在一个数组中,将它们设置为视图参数,然后渲染我的页面。
编辑:到目前为止,我已经尝试了以下
班级
<?php
namespace common\models;
use Yii;
class Notificacoes
{
private $listaNotificacoes;
public function __construct($id, $name)
{
$this->listaNotificacoes = array();
$server = "127.0.0.1";
$port = 1883;
$username = "";
$password = "";
$client_id = $id;
$mqtt = new \common\mosquitto\phpMQTT($server, $port, $client_id);
if(!$mqtt->connect(true, NULL, $username, $password)) {
exit(1);
}
$topics[$name] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
while($mqtt->proc()){
}
$mqtt->close();
}
function procmsg($topic, $msg)
{
\array_push($this->listaNotificacoes, $msg);
}
public function getAll()
{
return $this->listaNotificacoes;
}
}
SiteController:我试图在 beforeAction 方法上获取消息
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
$notifications = array();
if (!Yii::$app->user->isGuest)
{
$notifs = new Notificacoes(Yii::$app->user->identity->getId(), Yii::$app->user->identity->username);
$notifications = $notifs->getAll();
}
$this->view->params['notifications'] = $notifications;
return true;
}