I have an yii2
project with the advanced template and I want to implement notifications using a mosquitto broker
.
I already have the publish part done and working, now I'd like to have some help on subscribing to a topic on my frontend app. I already tried, but the page seems to stop working when I subscribe to any topic.
Is there any easy way or tutorial that I can use? If any more information is needed, please ask.
P.S: My idea was: When I open any page on frontend, I check for messages, save them in a array, set them as view param and then render my page.
EDIT: So far i've tried the following
Class
<?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: I tried to get the messages on the beforeAction method
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;
}