ios pusher使用

tech2022-07-06  191

ios pusher使用

This article was peer reviewed by Rafie Younes and Wern Ancheta. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

本文由Rafie Younes和Wern Ancheta进行了同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态!



The modern web user expects to be informed of everything that happens within the application. You don’t want to be that one website that doesn’t even have the notifications dropdown found not just in all social media websites, but everywhere else these days, too.

现代的Web用户希望了解应用程序内发生的所有事情。 您不希望成为一个没有通知下拉列表的网站,不仅在所有社交媒体网站中找到,而且在如今的所有其他地方也都找不到。

Luckily, with Laravel and Pusher, implementing this functionality is a breeze. The code we’ll write in this tutorial can be found here.

幸运的是,使用Laravel和Pusher可以轻松实现此功能。 我们将在本教程中编写的代码可以在这里找到。

Image via Pusher.com

图片来自Pusher.com

实时通知 (Real-Time Notifications)

In order to provide users with a good experience, notifications should to be shown in real-time. One approach is to send an AJAX request regularly to the back end and fetch the newest notifications if they exist.

为了给用户带来良好的体验,应该实时显示通知。 一种方法是定期将AJAX请求发送到后端,并获取最新的通知(如果存在)。

A better approach is to leverage the power of WebSockets, and receive notifications the moment they are sent. This is what we’re going to use in this tutorial.

更好的方法是利用WebSocket的功能 ,并在发送消息时立即接收通知。 这就是本教程要使用的内容。

推杆 (Pusher)

Pusher is a web service for

Pusher是一个Web服务,用于

… integrating realtime bi-directional functionality via WebSockets to web and mobile apps.

…通过WebSocket将实时双向功能集成到Web和移动应用程序。

It has a very simple API, but we’re going to make using it even simpler with Laravel Broadcasting and Laravel Echo.

它有一个非常简单的API,但是我们将通过Laravel Broadcasting和Laravel Echo使它更加简单。

In this tutorial, we’re going to add real-time notifications to an existing blog. The basic functionality is similar to Real-Time Laravel Notifications with Stream. We’ll start off with this repo made by Christopher Vundi (I changed it just a bit) which is a simple blog where users that can perform CRUD on posts.

在本教程中,我们将向现有博客添加实时通知。 基本功能类似于带有Stream的实时Laravel通知 。 我们将从克里斯托弗·冯迪 ( Christopher Vundi)制作的这个 仓库开始 (我对此做了一点修改),这是一个简单的博客,用户可以在其上执行CRUD。

该项目 (The Project)

初始化 (Initialization)

First we’ll clone the simple Laravel blog:

首先,我们将克隆简单的Laravel博客:

git clone https://github.com/vickris/simple-blog

Then we’ll create a MySQL database and set up environment variables to give the application access to the database.

然后,我们将创建一个MySQL数据库并设置环境变量,以使应用程序可以访问数据库。

Let’s copy env.example to .env and update the database related variables.

让我们将env.example复制到.env并更新与数据库相关的变量。

cp .env.example .env DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret

.env

.env

Now let’s install the project’s dependencies with

现在让我们使用以下命令安装项目的依赖项

composer install

And run the migration and seeding command to populate the database with some data:

并运行migration and seeding命令以使用一些数据填充数据库:

php artisan migrate --seed

If you run the application and visit /posts you’ll be able to see a listing of generated posts. Check the application, register a user, and create some posts. It’s a very basic app, but serves our demo perfectly.

如果您运行该应用程序并访问/posts则将看到生成的帖子列表。 检查应用程序,注册用户,并创建一些帖子。 这是一个非常基本的应用程序,但是可以完美地演示我们的演示。

关注用户关系 (Follow Users Relationships)

We want to give users the ability to follow other users, and be followed by users, so we have to create a Many To Many relationship between users to make it happen.

我们希望赋予用户跟随其他用户并被用户跟随的能力,因此我们必须在用户之间创建Many To Many关系以使其实现。

Let’s make a pivot table that relates users to users. Make a new followers migration:

让我们创建一个将用户与用户联系起来的数据透视表。 进行新的followers迁移:

php artisan make:migration create_followers_table --create=followers

We need to add some fields to that migration: a user_id to represent the user who is following, and a follows_id field to represent the user who’s being followed.

我们需要为该迁移添加一些字段:一个user_id代表正在关注的用户,一个follows_id字段代表正在关注的用户。

Update the migration as follows:

更新迁移,如下所示:

public function up() { Schema::create('followers', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->index(); $table->integer('follows_id')->index(); $table->timestamps(); }); }

Now let’s migrate to create the table:

现在,让我们迁移以创建表:

php artisan migrate

If you have followed the Stream approach article you’ll find that things are almost identical up to this point. In the part that follows, we’re going to achieve the same follow functionality with a different approach.

如果您已经阅读了Stream方法文章,那么到那时为止,您会发现事情几乎是相同的。 在接下来的部分中,我们将使用不同的方法来实现相同的跟随功能。

Let’s add relationships methods to the User model.

让我们向User模型添加关系方法。

// ... class extends Authenticatable { // ... public function followers() { return $this->belongsToMany(self::class, 'followers', 'follows_id', 'user_id') ->withTimestamps(); } public function follows() { return $this->belongsToMany(self::class, 'followers', 'user_id', 'follows_id') ->withTimestamps(); } }

app/User.php

app/User.php

Now that the user model has the necessary relationships, followers returns all the followers of a user, and follows returns everyone the user is following.

现在用户模型具有必要的关系, followers返回用户的所有关注者,而follows返回用户所关注的每个人。

We’ll be needing some helper functions to allow the user to follow another user, and to check whether a user isFollowing a specific user.

我们将需要一些帮助程序功能,以允许该用户follow另一个用户,并检查该用户是否在isFollowing特定用户。

// ... class extends Authenticatable { // ... public function follow($userId) { $this->follows()->attach($userId); return $this; } public function unfollow($userId) { $this->follows()->detach($userId); return $this; } public function isFollowing($userId) { return (boolean) $this->follows()->where('follows_id', $userId)->first(['id']); } }

app/User.php

app/User.php

Perfect. With the model set, it’s time to list users.

完善。 设置好模型后,就该列出用户了。

列出用户 (Listing Users)

Let’s start by setting the necessary routes

让我们从设置必要的路线开始

//... Route::group(['middleware' => 'auth'], function () { Route::get('users', 'UsersController@index')->name('users'); Route::post('users/{user}/follow', 'UsersController@follow')->name('follow'); Route::delete('users/{user}/unfollow', 'UsersController@unfollow')->name('unfollow'); });

routes/web.php

routes/web.php

Then, it’s time to create a new controller for users:

然后,该为用户创建一个新的控制器了:

php artisan make:controller UsersController

We’ll add an index method to it:

我们将为其添加index方法:

// ... use App\User; class UsersController extends Controller { //.. public function index() { $users = User::where('id', '!=', auth()->user()->id)->get(); return view('users.index', compact('users')); } }

app/Http/Controllers/UsersController.php

app/Http/Controllers/UsersController.php

The method needs a view. Let’s create the users.index view and put this markup in it:

该方法需要一个视图。 让我们创建users.index视图并将此标记放入其中:

@extends('layouts.app') @section('content') <div class="container"> <div class="col-sm-offset-2 col-sm-8"> <!-- Following --> <div class="panel panel-default"> <div class="panel-heading"> All Users </div> <div class="panel-body"> <table class="table table-striped task-table"> <thead> <th>User</th> <th> </th> </thead> <tbody> @foreach ($users as $user) <tr> <td clphpass="table-text"><div>{{ $user->name }}</div></td> @if (auth()->user()->isFollowing($user->id)) <td> <form action="{{route('unfollow', ['id' => $user->id])}}" method="POST"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" id="delete-follow-{{ $user->id }}" class="btn btn-danger"> <i class="fa fa-btn fa-trash"></i>Unfollow </button> </form> </td> @else <td> <form action="{{route('follow', ['id' => $user->id])}}" method="POST"> {{ csrf_field() }} <button type="submit" id="follow-user-{{ $user->id }}" class="btn btn-success"> <i class="fa fa-btn fa-user"></i>Follow </button> </form> </td> @endif </tr> @endforeach </tbody> </table> </div> </div> </div> </div> @endsection

resources/views/users/index.blade.php

resources/views/users/index.blade.php

You can now visit the /users page to see a listing of users.

现在,您可以访问/users页面以查看用户列表。

跟随或取消关注 (To Follow, or to Unfollow)

The UsersController lacks follow and unfollow methods. Let’s get them done to wrap this part up.

UsersController缺少follow和unfollow方法。 让我们来完成它们,以完成这一部分。

//... class UsersController extends Controller { //... public function follow(User $user) { $follower = auth()->user(); if ($follower->id == $user->id) { return back()->withError("You can't follow yourself"); } if(!$follower->isFollowing($user->id)) { $follower->follow($user->id); // sending a notification $user->notify(new UserFollowed($follower)); return back()->withSuccess("You are now friends with {$user->name}"); } return back()->withError("You are already following {$user->name}"); } public function unfollow(User $user) { $follower = auth()->user(); if($follower->isFollowing($user->id)) { $follower->unfollow($user->id); return back()->withSuccess("You are no longer friends with {$user->name}"); } return back()->withError("You are not following {$user->name}"); } }

app/Http/Controllers/UsersController.php

app/Http/Controllers/UsersController.php

We’re done with the follow functionality. We can now follow and unfollow users from the /users page.

我们已经完成了以下功能。 现在,我们可以在/users页面上关注和取消关注用户。

通知事项 (Notifications)

Laravel provides an API for sending notifications through multiple channels. Emails, SMS, web notifications, and any other type of notifications can all be sent using the Notification class.

Laravel提供了一个用于通过多个渠道发送通知的API。 电子邮件,SMS,Web通知和任何其他类型的通知都可以使用Notification类发送。

We are going to have two types of notifications:

我们将有两种类型的通知:

Follow notification: sent to a user when they get followed by another user

跟踪通知:在其他用户关注时发送给用户 Post created notification: sent to the followers of a given user when they create a new post

帖子创建通知:在创建新帖子时发送给给定用户的关注者

用户关注的通知 (User Followed Notification)

Using artisan commands, we can generate a migration for notifications:

使用artisan命令,我们可以为通知生成迁移:

php artisan notifications:table

Let’s migrate and create this new table.

让我们迁移并创建此新表。

php artisan migrate

We’re starting with follow notifications. Let’s execute this command to generate a notification class:

我们从关注通知开始。 让我们执行以下命令来生成通知类:

php artisan make:notification UserFollowed

Then we’ll update the notification class file we just created:

然后,我们将更新刚刚创建的通知类文件:

class UserFollowed extends Notification implements ShouldQueue { use Queueable; protected $follower; public function __construct(User $follower) { $this->follower = $follower; } public function via($notifiable) { return ['database']; } public function toDatabase($notifiable) { return [ 'follower_id' => $this->follower->id, 'follower_name' => $this->follower->name, ]; } }

app/Notifications/UserFollowed.php

app/Notifications/UserFollowed.php

With these few lines of code we can achieve a lot. First we’re requiring an instance of the $follower to be injected when this notification is created.

使用这几行代码,我们可以实现很多目标。 首先,我们需要在创建此通知时注入$follower的实例。

Using the via method, we’re telling Laravel to send this notification via the database channel. When Laravel encounters this, it will create a new record in the notifications table.

使用via方法,我们告诉Laravel通过database通道发送此通知。 当Laravel遇到此问题时,它将在通知表中创建一个新记录。

The user_id and notification type are automatically set, plus we can extend the notification with more data. That’s what toDatabase is for. The returned array will be added to the data field of the notification.

user_id和通知type是自动设置的,另外我们可以用更多数据扩展通知。 那就是toDatabase目的。 返回的数组将添加到通知的data字段中。

Finally, by implementing ShouldQueue, Laravel will automatically put this notification inside a queue to be executed in the background, which will speed up the response. This makes sense because we will be adding HTTP calls when we use Pusher later on.

最后,通过实现ShouldQueue ,Laravel将自动将此通知放入要在后台执行的队列中,这将加快响应速度。 这是有道理的,因为稍后我们将使用Pusher时将添加HTTP调用。

Let’s initiate the notification when the user gets followed.

让我们在用户受到关注时启动通知。

// ... use App\Notifications\UserFollowed; class UsersController extends Controller { // ... public function follow(User $user) { $follower = auth()->user(); if ( ! $follower->isFollowing($user->id)) { $follower->follow($user->id); // add this to send a notification $user->notify(new UserFollowed($follower)); return back()->withSuccess("You are now friends with {$user->name}"); } return back()->withSuccess("You are already following {$user->name}"); } //... }

app/Http/Controllers/UsersController.php

app/Http/Controllers/UsersController.php

We could call the notify method on a User model because it is already using the Notifiable trait. Any model you want to notify should be using it to get access to the notify method.

我们可以在User模型上调用notify方法,因为它已经在使用Notifiable特征。 您要通知的任何模型都应使用它来访问notify方法。

将通知标记为已读 (Mark a Notification as Read)

Notifications will contain some information and a link to a resource. For example: when a user receives a notification about a new post, the notification should show an informative text, redirect the user to the post when clicked, and be flagged as read.

通知将包含一些信息和资源链接。 例如:当用户收到有关新帖子的通知时,该通知应显示信息性文本,单击后将用户重定向到该帖子,并标记为已读。

We’re going to make a middleware that checks if a request has a ?read=notification_id input and flag it as read.

我们将制作一个中间件,以检查请求是否具有?read=notification_id输入并将其标记为已读。

Let’s make a middleware with the following command:

让我们使用以下命令制作中间件:

php artisan make:middleware MarkNotificationAsRead

Then, let’s put this code inside the handle method of the middleware:

然后,将这段代码放入中间件的handle方法中:

class MarkNotificationAsRead { public function handle($request, Closure $next) { if($request->has('read')) { $notification = $request->user()->notifications()->where('id', $request->read)->first(); if($notification) { $notification->markAsRead(); } } return $next($request); } }

app/Http/Middleware/MarkNotificationAsRead.php

app/Http/Middleware/MarkNotificationAsRead.php

In order to get our middleware to be executed for each request, we’ll add it to $middlewareGroups.

为了使我们的中间件能够针对每个请求执行,我们将其添加到$middlewareGroups 。

//... class Kernel extends HttpKernel { //... protected $middlewareGroups = [ 'web' => [ //... \App\Http\Middleware\MarkNotificationAsRead::class, ], // ... ]; //... }

app/Http/Kernel.php

app/Http/Kernel.php

With that done, let’s show some notifications.

完成后,让我们显示一些通知。

显示通知 (Showing Notifications)

We have to show a listing of the notifications using AJAX, then update it in real time with Pusher. First, let’s add a notifications method to the controller:

我们必须使用AJAX显示通知列表,然后使用Pusher实时更新。 首先,让我们向控制器添加一个notifications方法:

// ... class UsersController extends Controller { // ... public function notifications() { return auth()->user()->unreadNotifications()->limit(5)->get()->toArray(); } }

app/Http/Controllers/UsersController.php

app/Http/Controllers/UsersController.php

This will return the last 5 unread notifications. We just have to add a route to make it accessible.

这将返回最后5条未读的通知。 我们只需要添加一条路由即可访问它。

//... Route::group([ 'middleware' => 'auth' ], function () { // ... Route::get('/notifications', 'UsersController@notifications'); });

routes/web.php

routes/web.php

Now add a dropdown for notifications in the header.

现在,在标题中添加通知下拉列表。

<head> <!-- // ... // --> <!-- Scripts --> <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?> </script> <!-- This makes the current user's id available in javascript --> @if(!auth()->guest()) <script> window.Laravel.userId = <?php echo auth()->user()->id; ?> </script> @endif </head> <body> <!-- // ... // --> @if (Auth::guest()) <li><a href="{{ url('/login') }}">Login</a></li> <li><a href="{{ url('/register') }}">Register</a></li> @else <!-- // add this dropdown // --> <li class="dropdown"> <a class="dropdown-toggle" id="notifications" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <span class="glyphicon glyphicon-user"></span> </a> <ul class="dropdown-menu" aria-labelledby="notificationsMenu" id="notificationsMenu"> <li class="dropdown-header">No notifications</li> </ul> </li> <!-- // ... // -->

resources/views/layouts/app.blade.php

resources/views/layouts/app.blade.php

We’ve also added a global window.Laravel.userId variable inside a script to get the current user’s ID.

我们还在脚本内添加了一个全局window.Laravel.userId变量,以获取当前用户的ID。

JavaScript和SASS (JavaScript and SASS)

We’re going to use Laravel Mix to compile JavaScript and SASS. First, we need to install npm packages.

我们将使用Laravel Mix来编译JavaScript和SASS。 首先,我们需要安装npm软件包。

npm install

Now let’s add this code into app.js:

现在,将这段代码添加到app.js :

window._ = require('lodash'); window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); var notifications = []; const NOTIFICATION_TYPES = { follow: 'App\\Notifications\\UserFollowed' };

app/resources/assets/js/app.js

app/resources/assets/js/app.js

This is just an initialization. We’re going to use notifications to store all notification objects whether they’re retrieved via AJAX or Pusher.

这只是一个初始化。 我们将使用notifications来存储所有通知对象,无论它们是通过AJAX还是Pusher检索的。

You probably guessed it, NOTIFICATION_TYPES contains types of notifications.

您可能会猜到, NOTIFICATION_TYPES包含通知的类型。

Next, let’s “GET” notifications via AJAX.

接下来,让我们通过AJAX进行“获取”通知。

//... $(document).ready(function() { // check if there's a logged in user if(Laravel.userId) { $.get('/notifications', function (data) { addNotifications(data, "#notifications"); }); } }); function addNotifications(newNotifications, target) { notifications = _.concat(notifications, newNotifications); // show only last 5 notifications notifications.slice(0, 5); showNotifications(notifications, target); }

app/resources/assets/js/app.js

app/resources/assets/js/app.js

With this, we’re getting the latest notifications from our API and putting them inside the dropdown.

这样,我们就可以从API中获取最新的通知,并将其放入下拉列表中。

Inside addNotifications we concatenate the present notifications with the new ones using Lodash, and take only the latest 5 to be shown.

在addNotifications内部,我们使用Lodash将当前通知与新通知连接起来,仅显示最新的5条。

We need a few more functions to finish the job.

我们还需要一些其他功能来完成这项工作。

//... function showNotifications(notifications, target) { if(notifications.length) { var htmlElements = notifications.map(function (notification) { return makeNotification(notification); }); $(target + 'Menu').html(htmlElements.join('')); $(target).addClass('has-notifications') } else { $(target + 'Menu').html('<li class="dropdown-header">No notifications</li>'); $(target).removeClass('has-notifications'); } }

app/resources/assets/js/app.js

app/resources/assets/js/app.js

This function builds a string of all notifications and puts it inside the dropdown. If no notifications were received, it just shows “No notifications”.

此函数生成所有通知的字符串,并将其放入下拉列表中。 如果未收到任何通知,则仅显示“没有通知”。

It also adds a class to the dropdown button, which will just change its color when notifications exist. It’s a bit like Github’s notifications.

它还为下拉按钮添加了一个类,当存在通知时,它将仅更改其颜色。 有点像Github的通知。

Finally, some helper functions to make notification strings.

最后,一些辅助函数可以生成通知字符串。

//... // Make a single notification string function makeNotification(notification) { var to = routeNotification(notification); var notificationText = makeNotificationText(notification); return '<li><a href="' + to + '">' + notificationText + '</a></li>'; } // get the notification route based on it's type function routeNotification(notification) { var to = '?read=' + notification.id; if(notification.type === NOTIFICATION_TYPES.follow) { to = 'users' + to; } return '/' + to; } // get the notification text based on it's type function makeNotificationText(notification) { var text = ''; if(notification.type === NOTIFICATION_TYPES.follow) { const name = notification.data.follower_name; text += '<strong>' + name + '</strong> followed you'; } return text; }

app/resources/assets/js/app.js

app/resources/assets/js/app.js

Now we’ll just add this to our app.scss file:

现在,我们将其添加到我们的app.scss文件中:

//... #notifications.has-notifications { color: #bf5329 }

app/resources/assets/sass/app.scss

app/resources/assets/sass/app.scss

Let’s compile assets:

让我们编译资产:

npm run dev

If you try and follow a user now, they’ll get a notification. When they click it, they’ll be redirected to /users, plus the notification will disappear.

如果您现在尝试追随用户,他们会收到通知。 当他们单击它时,他们将被重定向到/users ,并且通知将消失。

新帖通知 (New Post Notification)

We’re going to notify followers when a user creates a new post.

当用户创建新帖子时,我们将通知关注者。

Let’s start by generating the notification class.

让我们从生成通知类开始。

php artisan make:notification NewPost

Let’s update the generated class as follows:

让我们更新生成的类,如下所示:

// .. use App\Post; use App\User; class NewArticle extends Notification implements ShouldQueue { // .. protected $following; protected $post; public function __construct(User $following, Post $post) { $this->following = $following; $this->post = $post; } public function via($notifiable) { return ['database']; } public function toDatabase($notifiable) { return [ 'following_id' => $this->following->id, 'following_name' => $this->following->name, 'post_id' => $this->post->id, ]; } }

app/Notifications/NewArticle.php

app/Notifications/NewArticle.php

Next, we need to send the notification. There are several ways we could do this. I like to use Eloquent Observers.

接下来,我们需要发送通知。 我们有几种方法可以做到这一点。 我喜欢使用雄辩的旁观者 。

Let’s make an observer for Post and listen to its events. We’ll create a new class: app/Observers/PostObserver.php

让我们成为Post的观察者,并听听其事件。 我们将创建一个新类: app/Observers/PostObserver.php

namespace App\Observers; use App\Notifications\NewPost; use App\Post; class PostObserver { public function created(Post $post) { $user = $post->user; foreach ($user->followers as $follower) { $follower->notify(new NewPost($user, $post)); } } }

Then, register the observer in AppServiceProvider:

然后,在AppServiceProvider注册观察者:

//... use App\Observers\PostObserver; use App\Post; class AppServiceProvider extends ServiceProvider { //... public function boot() { Post::observe(PostObserver::class); } //... }

app/Providers/AppServiceProvider.php

app/Providers/AppServiceProvider.php

Now we just need to format the message to be shown in JS:

现在我们只需要格式化要在JS中显示的消息即可:

// ... const NOTIFICATION_TYPES = { follow: 'App\\Notifications\\UserFollowed', newPost: 'App\\Notifications\\NewPost' }; //... function routeNotification(notification) { var to = `?read=${notification.id}`; if(notification.type === NOTIFICATION_TYPES.follow) { to = 'users' + to; } else if(notification.type === NOTIFICATION_TYPES.newPost) { const postId = notification.data.post_id; to = `posts/${postId}` + to; } return '/' + to; } function makeNotificationText(notification) { var text = ''; if(notification.type === NOTIFICATION_TYPES.follow) { const name = notification.data.follower_name; text += `<strong>${name}</strong> followed you`; } else if(notification.type === NOTIFICATION_TYPES.newPost) { const name = notification.data.following_name; text += `<strong>${name}</strong> published a post`; } return text; }

app/resources/assets/js/app.js

app/resources/assets/js/app.js

And voilà! Users are getting notifications about follows and new posts! Go ahead and try it out!

和瞧! 用户正在收到有关关注和新帖子的通知! 继续尝试!

使用Pusher进行实时 (Going Real-Time with Pusher)

It’s time to use Pusher to get notifications in real-time through websockets.

现在是时候使用Pusher通过websockets实时获取通知了。

Sign up for a free Pusher account at pusher.com and create a new app.

在pusher.com上注册免费的Pusher帐户并创建一个新应用。

... BROADCAST_DRIVER=pusher PUSHER_KEY= PUSHER_SECRET= PUSHER_APP_ID=

Set your account’s options inside the broadcasting config file:

在broadcasting配置文件中设置您帐户的选项:

//... 'connections' => [ 'pusher' => [ //... 'options' => [ 'cluster' => 'eu', 'encrypted' => true ], ], //...

config/broadcasting.php

config/broadcasting.php

Then we’ll register App\Providers\BroadcastServiceProvider in the providers array.

然后,我们将在providers数组中注册App\Providers\BroadcastServiceProvider 。

// ... 'providers' => [ // ... App\Providers\BroadcastServiceProvider //... ], //...

config/app.php

config/app.php

We should install Pusher’s PHP SDK and Laravel Echo now:

我们现在应该安装PusherPHP SDK和Laravel Echo:

composer require pusher/pusher-php-server npm install --save laravel-echo pusher-js

We have to set the notification data to be broadcast. Let’s update the UserFollowed notification:

我们必须设置要广播的通知数据。 让我们更新UserFollowed通知:

//... class UserFollowed extends Notification implements ShouldQueue { // .. public function via($notifiable) { return ['database', 'broadcast']; } //... public function toArray($notifiable) { return [ 'id' => $this->id, 'read_at' => null, 'data' => [ 'follower_id' => $this->follower->id, 'follower_name' => $this->follower->name, ], ]; } }

app/Notifications/UserFollowed.php

app/Notifications/UserFollowed.php

And NewPost:

和NewPost :

//... class NewPost extends Notification implements ShouldQueue { //... public function via($notifiable) { return ['database', 'broadcast']; } //... public function toArray($notifiable) { return [ 'id' => $this->id, 'read_at' => null, 'data' => [ 'following_id' => $this->following->id, 'following_name' => $this->following->name, 'post_id' => $this->post->id, ], ]; } }

app/Notifications/NewPost.php

app/Notifications/NewPost.php

The last thing we need to do is update our JS. Open app.js and add the following code

我们需要做的最后一件事是更新我们的JS。 打开app.js并添加以下代码

// ... window.Pusher = require('pusher-js'); import Echo from "laravel-echo"; window.Echo = new Echo({ broadcaster: 'pusher', key: 'your-pusher-key', cluster: 'eu', encrypted: true }); var notifications = []; //... $(document).ready(function() { if(Laravel.userId) { //... window.Echo.private(`App.User.${Laravel.userId}`) .notification((notification) => { addNotifications([notification], '#notifications'); }); } });

app/resources/assets/js/app.js

app/resources/assets/js/app.js

And we’re done here. Notifications are being added in real-time. You can now play with the app and see how notifications get updated.

我们在这里完成了。 通知是实时添加的。 您现在可以使用该应用程序,并查看通知的更新方式。

结论 (Conclusion)

Pusher has a very simple API that makes receiving real-time events incredibly easy. Coupled with Laravel notifications, we could send a notification through multiple channels (email, SMS, Slack, etc.) from one place. In this tutorial, we added user-following functionality to a simple blog, and enhanced it with the aforementioned tools to get some smooth real-time functionality.

Pusher具有非常简单的API,使接收实时事件变得异常简单。 结合Laravel通知,我们可以从一个地方通过多种渠道(电子邮件,SMS,Slack等)发送通知。 在本教程中,我们将用户跟踪功能添加到一个简单的博客中,并使用上述工具对其进行了增强,以获得一些流畅的实时功能。

There’s a lot more to Pusher and to Laravel notifications: in tandem, the services allow you to send pub/sub messages in real time to browsers, mobiles, and IOT devices. There’s also a presence API to get online/offline status of users.

Pusher和Laravel通知还有很多:串联服务使您可以将发布/订阅消息实时发送到浏览器,移动设备和IOT设备。 还有一个在线状态API,可获取用户的在线/离线状态。

Please check their respective documentations (Pusher docs, Pusher tutorials, Laravel docs) to explore them in more depth and utilize their true potential.

请检查它们各自的文档( Pusher文档 , Pusher教程 , Laravel文档 ),以更深入地探索它们并充分利用它们的真正潜力。

Let me hear what you’ve built with these technologies in the comments.

让我在评论中听到您使用这些技术构建的内容。

翻译自: https://www.sitepoint.com/add-real-time-notifications-laravel-pusher/

ios pusher使用

最新回复(0)