日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ios pusher使用_如何使用Pusher向Laravel添加实时通知

發布時間:2023/12/20 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ios pusher使用_如何使用Pusher向Laravel添加实时通知 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

ios pusher使用

現代網絡用戶希望了解應用程序內發生的所有事情。 您不希望成為一個沒有通知下拉列表的網站,不僅在所有社交媒體網站中找到,而且在如今的所有其他地方也都找不到。

幸運的是,使用Laravel和Pusher可以輕松實現此功能。

實時通知

為了向用戶提供良好的體驗,應實時顯示通知。 一種方法是定期將AJAX請求發送到后端,并獲取最新的通知(如果存在)。

更好的方法是利用WebSocket的功能,并在發送消息時立即接收通知。 這就是我們將在本文中使用的內容。

推桿

Pusher是一種Web服務,用于通過WebSocket將實時雙向功能集成到Web和移動應用程序。

它有一個非常簡單的API,但是我們將通過Laravel Broadcasting和Laravel Echo使它更加簡單。

在本文中,我們將向現有博客添加實時通知。

該項目

初始化

首先,我們將克隆簡單的Laravel博客:

gitclone https ://github.com/marslan-ali/laravel-blog

然后,我們將創建一個MySQL數據庫并設置環境變量,以使應用程序可以訪問數據庫。

讓我們將env.example復制到.env并更新與數據庫相關的變量。

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

現在讓我們使用以下命令安裝項目的依賴項

composerinstall

并運行migration and seeding命令以使用一些數據填充數據庫:

php artisan migrate--seed

如果您運行該應用程序并訪問/posts則將看到生成的帖子列表。

檢查應用程序,注冊用戶,并創建一些帖子。 這是一個非常基本的應用程序,但是可以完美地演示我們的演示。

關注用戶關系

我們希望賦予用戶跟隨其他用戶并被用戶關注的能力,因此我們必須在用戶之間創建Many To Many關系才能實現。

讓我們創建一個數據透視表,將用戶與用戶聯系起來。 進行新的followers遷移:

php artisan make:migration create_followers_table --create=followers

我們需要為該遷移添加一些字段:一個user_id代表正在關注的用戶,一個follows_id字段代表正在關注的用戶。

更新遷移,如下所示:

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

現在,讓我們遷移以創建表:

php artisan migrate

讓我們向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

現在用戶模型具有必要的關系, followers返回用戶的所有關注者,而follows返回用戶所關注的每個人。

我們將需要一些幫助程序功能,以允許該用戶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

完善。 設置好模型后,就該列出用戶了。

列出用戶

讓我們從設置必要的路線開始

/... 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

然后,該為用戶創建一個新的控制器了:

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

該方法需要一個視圖。 讓我們創建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

現在,您可以訪問/users頁面以查看用戶列表。

跟隨或取消關注

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

我們已經完成了以下功能。 現在,我們可以在/users頁面上關注和取消關注用戶。

通知事項

Laravel提供了一個用于通過多個渠道發送通知的API。 電子郵件,SMS,Web通知和任何其他類型的通知都可以使用Notification類發送。

我們將有兩種類型的通知:

  • 跟蹤通知:在其他用戶關注時發送給用戶
  • 帖子創建通知:發送給給定用戶的關注者,當他們創建新帖子時

用戶關注的通知

使用工匠命令,我們可以為通知生成遷移:

php artisan notifications:table

讓我們遷移并創建此新表。

php artisan migrate

我們從關注通知開始。 讓我們執行以下命令來生成通知類:

php artisan make :notification UserFollowed

然后,我們將更新剛剛創建的通知類文件:

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

使用這幾行代碼,我們可以實現很多目標。 首先,我們需要在創建此通知時注入$follower的實例。

使用via方法,我們告訴Laravel通過database通道發送此通知。 當Laravel遇到此問題時,它將在通知表中創建一個新記錄。

user_id和通知type是自動設置的,另外我們可以用更多數據擴展通知。 那就是toDatabase目的。 返回的數組將添加到通知的data字段。

最后,通過實現ShouldQueue ,Laravel將自動將該通知放入要在后臺執行的隊列中,這將加快響應速度。 這是有道理的,因為稍后將在使用Pusher時添加HTTP調用。

讓我們在用戶受到關注時啟動通知。

// ... 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模型上調用notify方法,因為它已經在使用Notifiable特征。

您要通知的任何模型都應使用它來訪問notify方法。

將通知標記為已讀

通知將包含一些信息和資源鏈接。 例如:當用戶收到有關新帖子的通知時,該通知應顯示信息性文本,單擊后將用戶重定向到該帖子,并標記為已讀。

我們將制作一個中間件,以檢查請求是否具有?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

為了使我們的中間件能夠針對每個請求執行,我們將其添加到$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

報表廣告

現在,在標題中添加通知下拉列表。

<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

我們還在腳本內添加了一個全局window.Laravel.userId變量,以獲取當前用戶的ID。

JavaScript和SASS

我們將使用Laravel Mix來編譯JavaScript和SASS。 首先,我們需要安裝npm軟件包。

npminstall

現在,將以下代碼添加到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內部,我們使用Lodash將當前通知與新通知連接起來 ,僅顯示最新的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

此函數生成所有通知的字符串,并將其放入下拉列表中。

如果未收到任何通知,則僅顯示“沒有通知”。

它還向下拉按鈕添加了一個類,當存在通知時,它將僅更改其顏色。 有點像Github的通知。

最后,一些幫助器函數可以生成通知字符串。

//... // 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.scss文件中:

//...#notifications .has-notifications {color : #bf5329 } app/resources/assets/sass/app.scss

讓我們編譯資產:

npmrun dev

如果您現在嘗試追隨用戶,他們會收到通知。 當他們單擊它時,他們將被重定向到/users ,并且通知將消失。

新帖通知

當用戶創建新帖子時,我們將通知關注者。

讓我們從生成通知類開始。

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

報表廣告

接下來,我們需要發送通知。 我們有幾種方法可以做到這一點。

我喜歡使用雄辯的旁觀者。

讓我們成為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));}} }

然后,在AppServiceProvider注冊觀察者:

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

現在我們只需要格式化要在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

和瞧! 用戶將收到有關關注和新帖子的通知! 繼續嘗試!

使用Pusher進行實時

是時候使用Pusher通過websockets實時獲取通知了。

在pusher.com上注冊免費的Pusher帳戶,然后創建一個新應用。

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

在broadcasting配置文件中設置您帳戶的選項:

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

然后,我們將在providers數組中注冊App \ Providers \ BroadcastServiceProvider。

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


我們現在應該安裝PusherPHP SDK和Laravel Echo:

config/app.php

報表廣告

composer require pusher/pusher-php-servernpm install --save laravel-echo pusher-js

我們必須設置要廣播的通知數據。 讓我們更新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

我們在這里完成了。 通知是實時添加的。 您現在可以使用該應用程序,并查看通知的更新方式。

結論

Pusher具有非常簡單的API,使接收實時事件變得異常簡單。 結合Laravel通知,我們可以從一個地方通過多個渠道(電子郵件,SMS,Slack等)發送通知。 在本教程中,我們將用戶跟蹤功能添加到一個簡單的博客中,并使用上述工具對其進行了增強,以獲得一些流暢的實時功能。

Pusher和Laravel通知還有很多:串聯服務使您可以將發布/訂閱消息實時發送到瀏覽器,移動設備和IOT設備。 還有一個在線狀態API,可獲取用戶的在線/離線狀態。

請檢查它們各自的文檔( Pusher文檔 , Pusher教程 , Laravel文檔 )以更深入地探索它們并充分利用它們的真正潛力。

如果您在任何類型的開發項目中需要幫助,我也可以為您提供有關項目的咨詢。 我是最受好評的自由職業者。 您可以直接在 Upwork 上雇用我 。 ? 你也可以雇用我 ? 自由職業者 。

如果您有任何評論,問題或建議,請隨時在下面的評論部分中發布它們!

翻譯自: https://hackernoon.com/how-to-add-real-time-notifications-to-laravel-with-pusher-6l12h3yqz

ios pusher使用

總結

以上是生活随笔為你收集整理的ios pusher使用_如何使用Pusher向Laravel添加实时通知的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。