我最近在我的PHP laravel项目中使用了pusher,它工作得很好。我对pusher的了解是,它是我们的服务器和客户端之间的一个实时层,并创建到客户端浏览器的web套接字连接。我使用以下教程在我的应用程序中安装了pusher:
我使用pusher为我的web应用程序创建的内容:
1.我创建了一个通知功能。当一个用户向数据库添加一些数据时,比如当一个用户开始跟踪其他用户时,就会触发一个事件,然后该事件将数据发送到专用通道,比如“通知-通道”,在我的js代码中,我订阅了这个通道。为此,我编写了以下代码:
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('68fd8888888888ee72c', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('notification-channel');
//Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\HelloPusherEvent', addMessage);但我认为使用pusher进行通知或任何其他功能是不正确的。此外,在我的项目中,我想使用pusher在用户的新闻提要上显示新的新闻提要,而不需要刷新页面,显然很少有用户会看到那些发布该消息的用户。
但是,如果客户端的条件停止显示数据,我将如何以一种不需要实现的方式使用pusher。在这里,我担心的是,如果我继续向所有活动客户端发送数据,并将if条件用于筛选最终会降低应用程序级别的数据。
My concerns:
如果我的问题不够明确和具体,请告诉我,我将进一步阐述。
预先感谢所有想要回答的人。
发布于 2017-01-05 05:21:35
推动者-应用程序-客户端-事件解释了这个问题,我们可以为不同的用户创建不同的通道,以便只向预期的用户发送msg。
通过这个常见问题,我知道我们可以为一个注册的应用程序创建无限的渠道。
创建多个通道不会造成任何开销。
现在,如果我想发送通知给用户1,那么我将创建一个通道‘通知-通道-1’,并将订阅用户1到我的前端代码中的同一个频道。
我在PHP laravel项目中使用的事件类如下所示:
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
/**
* Just implement the ShouldBroadcast interface and Laravel will automatically
* send it to Pusher once we fire it
**/
class HelloPusherEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
/**
* Only (!) Public members will be serialized to JSON and sent to Pusher
**/
public $message;
public $id;
public $for_user_id;
/**
* Create a new event instance.
* @param string $message (notification description)
* @param integer $id (notification id)
* @param integer $for_user_id (receiver's id)
* @author hkaur5
* @return void
*/
public function __construct($message,$id, $for_user_id)
{
$this->message = $message;
$this->id = $id;
$this->for_user_id = $for_user_id;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
//We have created names of channel on basis of user's id who
//will receive data from this class.
//See frontend pusher code to see how we have used this channel
//for intended user.
return ['notification-channel_'.$this->for_user_id];
}
}在前端,我订阅了“通知-通道-”+logged_in_user_id
//Subscribe to the channel we specified in our Laravel Event
//Subscribe user to the channel created for this user.
//For example if user's id is 1 then bind to notification-channel_1
var channel = pusher.subscribe('notification-channel_'+$('#logged_in_userId').val());
//Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\HelloPusherEvent', addMessage);通过这种方式,我们只能将数据发送给预期的用户,而不是通过在客户端代码中添加条件来阻止所有用户接收到的数据。
发布于 2020-04-27 22:00:15
我认为您应该直接在Blade模板中添加用户ID,而不是使用表单字段:
var channel = pusher.subscribe('notification-channel_{{ Auth::id() }}');https://stackoverflow.com/questions/41428318
复制相似问题