ios pusher使用_如何使用Pusher向Laravel添加实时通知
ios pusher使用
現(xiàn)代網(wǎng)絡(luò)用戶希望了解應(yīng)用程序內(nèi)發(fā)生的所有事情。 您不希望成為一個沒有通知下拉列表的網(wǎng)站,不僅在所有社交媒體網(wǎng)站中找到,而且在如今的所有其他地方也都找不到。
幸運的是,使用Laravel和Pusher可以輕松實現(xiàn)此功能。
實時通知
為了向用戶提供良好的體驗,應(yīng)實時顯示通知。 一種方法是定期將AJAX請求發(fā)送到后端,并獲取最新的通知(如果存在)。
更好的方法是利用WebSocket的功能,并在發(fā)送消息時立即接收通知。 這就是我們將在本文中使用的內(nèi)容。
推桿
Pusher是一種Web服務(wù),用于通過WebSocket將實時雙向功能集成到Web和移動應(yīng)用程序。
它有一個非常簡單的API,但是我們將通過Laravel Broadcasting和Laravel Echo使它更加簡單。
在本文中,我們將向現(xiàn)有博客添加實時通知。
該項目
初始化
首先,我們將克隆簡單的Laravel博客:
gitclone https ://github.com/marslan-ali/laravel-blog然后,我們將創(chuàng)建一個MySQL數(shù)據(jù)庫并設(shè)置環(huán)境變量,以使應(yīng)用程序可以訪問數(shù)據(jù)庫。
讓我們將env.example復(fù)制到.env并更新與數(shù)據(jù)庫相關(guān)的變量。
cp .env.example .envDB_HOST =localhost DB_DATABASE =homestead DB_USERNAME =homestead DB_PASSWORD =secret現(xiàn)在讓我們使用以下命令安裝項目的依賴項
composerinstall并運行migration and seeding命令以使用一些數(shù)據(jù)填充數(shù)據(jù)庫:
php artisan migrate--seed如果您運行該應(yīng)用程序并訪問/posts則將看到生成的帖子列表。
檢查應(yīng)用程序,注冊用戶,并創(chuàng)建一些帖子。 這是一個非?;镜膽?yīng)用程序,但是可以完美地演示我們的演示。
關(guān)注用戶關(guān)系
我們希望賦予用戶跟隨其他用戶并被用戶關(guān)注的能力,因此我們必須在用戶之間創(chuàng)建Many To Many關(guān)系才能實現(xiàn)。
讓我們創(chuàng)建一個數(shù)據(jù)透視表,將用戶與用戶聯(lián)系起來。 進行新的followers遷移:
php artisan make:migration create_followers_table --create=followers我們需要為該遷移添加一些字段:一個user_id代表正在關(guān)注的用戶,一個follows_id字段代表正在關(guān)注的用戶。
更新遷移,如下所示:
public function up () {Schema::create( 'followers' , function (Blueprint $table) {$table->increments( 'id' );$table->integer( 'user_id' )->index();$table->integer( 'follows_id' )->index();$table->timestamps();}); }現(xiàn)在,讓我們遷移以創(chuàng)建表:
php artisan migrate讓我們向User模型添加關(guān)系方法。
// ...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現(xiàn)在用戶模型具有必要的關(guān)系, followers返回用戶的所有關(guān)注者,而follows返回用戶所關(guān)注的每個人。
我們將需要一些幫助程序功能,以允許該用戶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完善。 設(shè)置好模型后,就該列出用戶了。
列出用戶
讓我們從設(shè)置必要的路線開始
/... 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然后,該為用戶創(chuàng)建一個新的控制器了:
php artisan make :controller UsersController我們將為其添加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該方法需要一個視圖。 讓我們創(chuàng)建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現(xiàn)在,您可以訪問/users頁面以查看用戶列表。
跟隨或取消關(guān)注
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我們已經(jīng)完成了以下功能。 現(xiàn)在,我們可以在/users頁面上關(guān)注和取消關(guān)注用戶。
通知事項
Laravel提供了一個用于通過多個渠道發(fā)送通知的API。 電子郵件,SMS,Web通知和任何其他類型的通知都可以使用Notification類發(fā)送。
我們將有兩種類型的通知:
- 跟蹤通知:在其他用戶關(guān)注時發(fā)送給用戶
- 帖子創(chuàng)建通知:發(fā)送給給定用戶的關(guān)注者,當(dāng)他們創(chuàng)建新帖子時
用戶關(guān)注的通知
使用工匠命令,我們可以為通知生成遷移:
php artisan notifications:table讓我們遷移并創(chuàng)建此新表。
php artisan migrate我們從關(guān)注通知開始。 讓我們執(zhí)行以下命令來生成通知類:
php artisan make :notification UserFollowed然后,我們將更新剛剛創(chuàng)建的通知類文件:
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使用這幾行代碼,我們可以實現(xiàn)很多目標。 首先,我們需要在創(chuàng)建此通知時注入$follower的實例。
使用via方法,我們告訴Laravel通過database通道發(fā)送此通知。 當(dāng)Laravel遇到此問題時,它將在通知表中創(chuàng)建一個新記錄。
user_id和通知type是自動設(shè)置的,另外我們可以用更多數(shù)據(jù)擴展通知。 那就是toDatabase目的。 返回的數(shù)組將添加到通知的data字段。
最后,通過實現(xiàn)ShouldQueue ,Laravel將自動將該通知放入要在后臺執(zhí)行的隊列中,這將加快響應(yīng)速度。 這是有道理的,因為稍后將在使用Pusher時添加HTTP調(diào)用。
讓我們在用戶受到關(guān)注時啟動通知。
// ... 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報表廣告
我們可以在User模型上調(diào)用notify方法,因為它已經(jīng)在使用Notifiable特征。
您要通知的任何模型都應(yīng)使用它來訪問notify方法。
將通知標記為已讀
通知將包含一些信息和資源鏈接。 例如:當(dāng)用戶收到有關(guān)新帖子的通知時,該通知應(yīng)顯示信息性文本,單擊后將用戶重定向到該帖子,并標記為已讀。
我們將制作一個中間件,以檢查請求是否具有?read=notification_id輸入并將其標記為已讀。
讓我們使用以下命令制作中間件:
php artisan make:middleware MarkNotificationAsRead然后,將這段代碼放入中間件的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為了使我們的中間件能夠針對每個請求執(zhí)行,我們將其添加到$middlewareGroups 。
//... class Kernel extends HttpKernel {//...protected $middlewareGroups = ['web' => [//...\App\Http\Middleware\MarkNotificationAsRead::class,],// ...];//... } app/Http/Kernel.php完成后,讓我們顯示一些通知。
顯示通知
我們必須使用AJAX顯示通知列表,然后使用Pusher實時更新。 首先,讓我們向控制器添加一個notifications方法:
// ... class UsersController extends Controller {// ...public function notifications () {return auth()->user()->unreadNotifications()->limit( 5 )->get()->toArray();} } app/Http/Controllers/UsersController.php這將返回最后5條未讀的通知。 我們只需要添加一條路由即可訪問它。
//... Route::group([ 'middleware' => 'auth' ], function () {// ...Route::get( '/notifications' , 'UsersController@notifications' ); }); routes/web.php報表廣告
現(xiàn)在,在標題中添加通知下拉列表。
<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我們還在腳本內(nèi)添加了一個全局window.Laravel.userId變量,以獲取當(dāng)前用戶的ID。
JavaScript和SASS
我們將使用Laravel Mix來編譯JavaScript和SASS。 首先,我們需要安裝npm軟件包。
npminstall現(xiàn)在,將以下代碼添加到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這只是一個初始化。 無論是通過AJAX還是Pusher檢索它們,我們都將使用通知來存儲所有通知對象。
您可能會猜到, NOTIFICATION_TYPES包含通知的類型。
接下來,讓我們通過AJAX進行“ GET”通知。
//... $( document ).ready( function () {// check if there's a logged in userif (Laravel.userId) {$.get( '/notifications' , function ( data ) {addNotifications(data, "#notifications" );});} }); function addNotifications ( newNotifications, target ) {notifications = _.concat(notifications, newNotifications);// show only last 5 notificationsnotifications.slice( 0 , 5 );showNotifications(notifications, target); }app/resources/assets/js/app.js
這樣,我們就可以從API中獲取最新的通知,并將其放入下拉列表中。
在addNotifications內(nèi)部,我們使用Lodash將當(dāng)前通知與新通知連接起來 ,僅顯示最新的5條。
我們還需要一些其他功能來完成這項工作。
報表廣告
//... 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此函數(shù)生成所有通知的字符串,并將其放入下拉列表中。
如果未收到任何通知,則僅顯示“沒有通知”。
它還向下拉按鈕添加了一個類,當(dāng)存在通知時,它將僅更改其顏色。 有點像Github的通知。
最后,一些幫助器函數(shù)可以生成通知字符串。
//... // 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現(xiàn)在,我們將其添加到我們的app.scss文件中:
//...#notifications .has-notifications {color : #bf5329 } app/resources/assets/sass/app.scss讓我們編譯資產(chǎn):
npmrun dev如果您現(xiàn)在嘗試追隨用戶,他們會收到通知。 當(dāng)他們單擊它時,他們將被重定向到/users ,并且通知將消失。
新帖通知
當(dāng)用戶創(chuàng)建新帖子時,我們將通知關(guān)注者。
讓我們從生成通知類開始。
php artisan make :notification NewPost讓我們更新生成的類,如下所示:
// .. 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報表廣告
接下來,我們需要發(fā)送通知。 我們有幾種方法可以做到這一點。
我喜歡使用雄辯的旁觀者。
讓我們成為Post的觀察者,并聽聽其事件。 我們將創(chuàng)建一個新類: 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));}} }然后,在AppServiceProvider注冊觀察者:
//... use App \ Observers \ PostObserver ; use App \ Post ; class AppServiceProvider extends ServiceProvider {//...public function boot () {Post::observe(PostObserver::class);}//... } app/Providers/AppServiceProvider.php現(xiàn)在我們只需要格式化要在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和瞧! 用戶將收到有關(guān)關(guān)注和新帖子的通知! 繼續(xù)嘗試!
使用Pusher進行實時
是時候使用Pusher通過websockets實時獲取通知了。
在pusher.com上注冊免費的Pusher帳戶,然后創(chuàng)建一個新應(yīng)用。
... BROADCAST_DRIVER=pusher PUSHER_KEY= PUSHER_SECRET= PUSHER_APP_ID=在broadcasting配置文件中設(shè)置您帳戶的選項:
//...'connections' => ['pusher' => [//...'options' => ['cluster' => 'eu' ,'encrypted' => true],],//... config/broadcasting.php然后,我們將在providers數(shù)組中注冊App \ Providers \ BroadcastServiceProvider。
// ... 'providers' => [// ...App\Providers\BroadcastServiceProvider//... ], //...
我們現(xiàn)在應(yīng)該安裝PusherPHP SDK和Laravel Echo:
報表廣告
composer require pusher/pusher-php-servernpm install --save laravel-echo pusher-js我們必須設(shè)置要廣播的通知數(shù)據(jù)。 讓我們更新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和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我們需要做的最后一件事是更新我們的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我們在這里完成了。 通知是實時添加的。 您現(xiàn)在可以使用該應(yīng)用程序,并查看通知的更新方式。
結(jié)論
Pusher具有非常簡單的API,使接收實時事件變得異常簡單。 結(jié)合Laravel通知,我們可以從一個地方通過多個渠道(電子郵件,SMS,Slack等)發(fā)送通知。 在本教程中,我們將用戶跟蹤功能添加到一個簡單的博客中,并使用上述工具對其進行了增強,以獲得一些流暢的實時功能。
Pusher和Laravel通知還有很多:串聯(lián)服務(wù)使您可以將發(fā)布/訂閱消息實時發(fā)送到瀏覽器,移動設(shè)備和IOT設(shè)備。 還有一個在線狀態(tài)API,可獲取用戶的在線/離線狀態(tài)。
請檢查它們各自的文檔( Pusher文檔 , Pusher教程 , Laravel文檔 )以更深入地探索它們并充分利用它們的真正潛力。
如果您在任何類型的開發(fā)項目中需要幫助,我也可以為您提供有關(guān)項目的咨詢。 我是最受好評的自由職業(yè)者。 您可以直接在 Upwork 上雇用我 。 ? 你也可以雇用我 ? 自由職業(yè)者 。
如果您有任何評論,問題或建議,請隨時在下面的評論部分中發(fā)布它們!
翻譯自: https://hackernoon.com/how-to-add-real-time-notifications-to-laravel-with-pusher-6l12h3yqz
ios pusher使用
總結(jié)
以上是生活随笔為你收集整理的ios pusher使用_如何使用Pusher向Laravel添加实时通知的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EXCEL文件中的VBA模块名包含中文名
- 下一篇: 百度2017春招-买帽子