[英]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. 问题1:-有一个消息系统。 Users are able to send each other messages.
用户能够互相发送消息。 I would like to have a real time pop up when the user gets a new message and is not on the inbox page.
当用户收到新消息且不在收件箱页面上时,我希望实时弹出。
Issue 2: - I would like to create a basic achievement system, one of the achievements could (for example) be: "Receive a message." 问题2:-我想创建一个基本的成就系统,其中一项成就可能(例如)是:“接收消息”。
Now I think both functionalities can be achieved through the same way. 现在,我认为这两种功能可以通过相同的方式实现。 Anyone of you has any experience with this type of real time communication?
你们中的任何人都具有这种实时通信的经验吗? I really have no idea where to start.
我真的不知道从哪里开始。 I would really love it if it is not to heavy.
如果它不重,我真的会喜欢它。
Thanks a lot. 非常感谢。
Here's a boilerplate you might use for long polling (using jQuery and Yii): 这是您可能用于长时间轮询(使用jQuery和Yii)的样板:
Server-side: 服务器端:
class MessagesController extends CController {
public function actionPoll( $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){
return array(
'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 again
for (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. 请记住要实施某种身份验证,以避免用户彼此阅读消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.