应用程序范围订阅频道

Application wide subscription to a channel

关于 Pusher.js 的快速问题。

我今天开始研究通知功能,想用 Pusher.js 来做这件事,因为我用它来聊天。

我在 Laravel 工作。我想要实现的是应用程序范围内的频道订阅。当用户注册时,正在为他创建一个频道 "notifications_channel",我将其存储在数据库中。我知道如何将用户注册到频道,但一旦他离开该页面,房间就会腾空。这不是我真正想要的,因为无论用户在平台上的哪个位置,我都想发送通知。

我在文档中找不到类似的东西,所以我想你们中的某个人可能知道如何这样做。

以下是我所做的一些片段:

当用户注册时,我触发:
$generateChannel = User::generateNotificationsChannel($request['email']);

这对应于我的模型:

public static function generateNotificationsChannel($email){
    $userID = User::getIdByMail($email);
    return self::where('email', $email)->update(['notifications_channel' => $userID."-".str_random(35)]);
}

这是相当基础的,但现在这就是我所需要的。

所以现在,当用户登录时,我的 HomeController 的 Index 函数被触发,它从数据库收集他的 NotificationsChannel 并将其发送到视图。

public function index()
{
    $notificationsChannel = User::getUserNotificationsChannel(\Auth::user()->id);
    return view('home', compact('notificationsChannel', $notificationsChannel));
}

到达那里后,我只需将用户订阅到该频道并将他绑定到链接到该频道的任何事件:

var notifications = pusher.subscribe('{{$notificationsChannel}}');
channel.bind('new-notification', notifyUser);

function notifyUser(data){
    console.log(data);
}

如您所见,目前它还很基础。但是我的调试控制台显示,一旦用户离开 /home,频道就会腾空。

那么问题来了,无论他在平台的哪个位置,我如何让他订阅频道?

我们将不胜感激任何帮助!

提前致谢。

我找到了解决这个问题的方法,我决定将通知通道发送到我的主布局,我用它来在用户登录后扩展所有视图。在我的主布局中,我订阅了用户到他自己的通知频道。

对于可能对我是如何做到的感兴趣的人:

我更改了 AppServiceProvider 的启动功能,您可以在 \app\Providers\AppServiceProvider 中找到它。代码如下所示:

public function boot()
{
    view()->composer('layouts.app', function($view){
        $channel = User::getUserNotificationsChannel(\Auth::user()->id);
        $view->with('data', array('channel' => $channel));
    });
}

在我的主布局中,我只是通过获取频道名称来订阅用户。