Yiiframework Message Pop Up
He there! If have a question that is related to two different issues I currently have in an application I'm working on. Issue 1: - There is a message system. Users are able to se
Solution 1:
Here's a boilerplate you might use for long polling (using jQuery and Yii):
Server-side:
classMessagesControllerextendsCController{
publicfunctionactionPoll($sincePk, $userPk) {
while (true) {
$messages = Message::model()->findAll([
'condition' => '`t`.`userId` = :userPk AND `t`.`id` > :sincePk',
'order' => '`t`.`id` ASC',
'params' => [ ':userPk' => (int)$userPk, ':sincePk' => (int)$sincePk ],
]);
if ($messages) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array_map(function($message){
returnarray(
'pk' => $message->primaryKey,
'from' => $message->from,
'text' => $message->text,
/* and whatever more information you want to send */
);
}, $messages));
}
sleep(1);
}
}
}
Client-side:
<?php$userPk = 1;
$lastMessage = Messages::model()->findByAttributes([ 'userId' => $userId ], [ 'order' => 'id ASC' ]);
$lastPk = $lastMessage ? $lastMessage->primaryKey : 0;
?>var poll = function( sincePk ) {
$.get('/messages/poll?sincePk='+sincePk+'&userPk=<?=$userPk?>').then(function(data) {
// the request ended, parse messages and poll againfor (var i = 0;i < data.length;i++)
alert(data[i].from+': '+data[i].text);
poll(data ? data[i].pk : sincePk);
}, function(){
// a HTTP error occurred (probable a timeout), just repoll
poll(sincePk);
});
}
poll(<?=$lastPk?>);
Remember to implement some kind of authentication to avoid users reading each others messages.
Post a Comment for "Yiiframework Message Pop Up"