如何使用 Laravel 和 Pusher 创建基于 Web 的通知
在构建 Web 应用程序时,我们经常会遇到应用内通知系统,它可以在有人对你或你的帐户执行相关操作时立即通知你。例如,在 Facebook 上,当有人点赞你的状态或评论你的个人主页时,你会收到通知。我们将使用Laravel和Pusher创建一个 Web 通知系统来复现这一功能。
我们将要建造的
本教程结束后,我们将演示如何使用 Laravel 和 Pusher 创建一个小型 Web 应用程序来显示通知。其效果类似于 Facebook 等网站显示通知的方式。以下是我们即将构建的应用程序的预览:

设置您的 Pusher 应用程序
如果您还没有Pusher 帐户,请创建一个,然后按照以下屏幕截图所示设置您的应用程序。
设置您的 Laravel 应用程序
您可以通过在终端中运行以下命令来创建一个新的 Laravel 应用程序:
laravel new laravel-web-notifications
之后,我们需要安装 Pusher PHP SDK,您可以使用 Composer 通过运行以下命令来完成此操作:
composer require pusher/pusher-php-server
Composer 配置完成后,我们需要配置 Laravel 使用 Pusher 作为其广播驱动程序。为此,请打开.envLaravel 安装根目录下的文件,并将文件中的值更新为与以下配置一致:
PUSHER_APP_ID=322700
BROADCAST_DRIVER=pusher
// Get the credentials from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX
重要提示:如果您使用的是欧盟或亚太集群,请务必更新配置
config/broadcasting.php文件中的选项数组,因为 Laravel 默认使用美国服务器。您可以使用 Pusher PHP 库支持的所有选项。
打开config/app.php并取消注释App\Providers\BroadcastServiceProvider::class。
创建我们的 Laravel 和 Pusher 应用程序
配置完成后,我们来创建应用程序。首先,我们需要创建一个Event类,用于从 Laravel 应用程序向 Pusher 广播事件。事件可以从应用程序中的任何位置触发。
php artisan make:event StatusLiked
这将StatusLiked在该app/Events目录中创建一个新类。打开该文件的内容并更新为以下内容:
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class StatusLiked implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($username)
{
$this->username = $username;
$this->message = "{$username} liked your status";
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['status-liked'];
}
}
上面我们已经实现了该ShouldBroadcast接口,这告诉 Laravel 应该使用我们在配置文件中设置的任何驱动程序来广播此事件。
我们还有一个构造函数,它接受两个参数:username 和 verb。稍后我们会详细介绍它。我们将这两个变量赋值给了同名的类属性。务必将这些属性的可见性设置为public;否则,该属性将被忽略。
最后,我们设置要广播的频道名称。
创建应用程序视图
我们将保持简洁,创建一个单一视图,其中包含一个带有通知图标的导航栏。当有新通知时,图标会自动更新,无需刷新页面。本教程中的通知是临时性的;您可以根据需要扩展此功能,使其在页面重新加载后持续显示更长时间。
打开welcome.blade.php文件并将其替换为以下HTML代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo Application</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="/css/bootstrap-notifications.min.css">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Demo App</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="dropdown dropdown-notifications">
<a href="#notifications-panel" class="dropdown-toggle" data-toggle="dropdown">
<i data-count="0" class="glyphicon glyphicon-bell notification-icon"></i>
</a>
<div class="dropdown-container">
<div class="dropdown-toolbar">
<div class="dropdown-toolbar-actions">
<a href="#">Mark all as read</a>
</div>
<h3 class="dropdown-toolbar-title">Notifications (<span class="notif-count">0</span>)</h3>
</div>
<ul class="dropdown-menu">
</ul>
<div class="dropdown-footer text-center">
<a href="#">View All</a>
</div>
</div>
</li>
<li><a href="#">Timeline</a></li>
<li><a href="#">Friends</a></li>
</ul>
</div>
</div>
</nav>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//js.pusher.com/3.1/pusher.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript">
var notificationsWrapper = $('.dropdown-notifications');
var notificationsToggle = notificationsWrapper.find('a[data-toggle]');
var notificationsCountElem = notificationsToggle.find('i[data-count]');
var notificationsCount = parseInt(notificationsCountElem.data('count'));
var notifications = notificationsWrapper.find('ul.dropdown-menu');
if (notificationsCount <= 0) {
notificationsWrapper.hide();
}
// Enable pusher logging - don't include this in production
// Pusher.logToConsole = true;
var pusher = new Pusher('API_KEY_HERE', {
encrypted: true
});
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('status-liked');
// Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\StatusLiked', function(data) {
var existingNotifications = notifications.html();
var avatar = Math.floor(Math.random() * (71 - 20 + 1)) + 20;
var newNotificationHtml = `
<li class="notification active">
<div class="media">
<div class="media-left">
<div class="media-object">
<img src="https://api.adorable.io/avatars/71/`+avatar+`.png" class="img-circle" alt="50x50" style="width: 50px; height: 50px;">
</div>
</div>
<div class="media-body">
<strong class="notification-title">`+data.message+`</strong>
<!--p class="notification-desc">Extra description can go here</p-->
<div class="notification-meta">
<small class="timestamp">about a minute ago</small>
</div>
</div>
</div>
</li>
`;
notifications.html(newNotificationHtml + existingNotifications);
notificationsCount += 1;
notificationsCountElem.attr('data-count', notificationsCount);
notificationsWrapper.find('.notif-count').text(notificationsCount);
notificationsWrapper.show();
});
</script>
</body>
</html>
这里大部分都是 Bootstrap 的冗余代码,所以我们会提取出重要的部分,主要是 JavaScript 代码。我们引入了Pusher JavaScript 库,然后添加了实现核心功能的 JavaScript 代码块。让我们来看一些 JavaScript 代码片段:
// Enable pusher logging - don't include this in production
// Pusher.logToConsole = true;
// Initiate the Pusher JS library
var pusher = new Pusher('API_KEY_HERE', {
encrypted: true
});
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('status-liked');
// Bind a function to a Event (the full Laravel class)
channel.bind('App\\Events\\StatusLiked', function(data) {
// this is called when the event notification is received...
});
小提示:默认情况下,Laravel 会使用事件的类名来广播事件。但是,您可以通过在事件上定义 broadcastAs 方法来自定义广播名称:
public function broadcastAs() {
返回'事件名称';
}
上面的代码只是初始化 Pusher JS 库并订阅一个频道。然后,它设置一个回调函数,以便在收到该频道上广播的事件时调用。
测试我们的设备
最后,为了测试我们的设置,我们将创建一个手动调用事件的路由。如果一切正常,每次访问该路由时,我们都会收到一条新的通知。让我们添加新路由:
Route::get('test', function () {
event(new App\Events\StatusLiked('Someone'));
return "Event has been sent!";
});
现在我们可以使用 Laravel 启动一个 PHP 服务器,以便测试我们的代码是否有效。
$ php artisan serve
结论
在本文中,我们利用 Pusher 的强大功能创建了一个现代化的 Web 通知系统,过程非常简单。但这仅仅是 Pusher 功能的冰山一角。这个示例只是为了向您展示其各种可能性。
代码已上传至GitHub,欢迎点赞、fork 并进行尝试。您打算如何使用 Laravel 和 Pusher?您能想到哪些高级用例?请在评论区留言!
本文最初发表于 Pusher Blog 。
文章来源:https://dev.to/neo/how-to-create-web-notifications-using-laravel-and-pusher-3b81
