Laravel과 Pusher를 사용하여 웹 기반 알림을 만드는 방법
뭐 공부 해요?
이 강좌 후에 Laravel과 Pusher를 사용하여 소형 웹 응용 프로그램에 알림을 표시하는 방법을 보여 드리겠습니다.이는 페이스북 등 사이트에서 알림을 표시하는 방식과 유사할 것이다.다음은 우리가 구축할 내용의 미리보기입니다.
![](https://s1.md5.ltd/image/762f6c195d142ffce7c9796c0543a817.gif)
Pusher 응용 프로그램 설정
Pusher account를 만듭니다. 만약 당신이 아직 없다면, 다음 화면 캡처와 같이 프로그램을 설정합니다.
![](https://s1.md5.ltd/image/8206cd84cf3f75dd1bd38fd8c191c807.png)
Laravel 응용 프로그램 설정
터미널에서 다음 명령을 실행하여 새 Laravel 응용 프로그램을 만들 수 있습니다.
laravel new laravel-web-notifications
그런 다음 Pusher PHP SDK를 설치해야 합니다. Composer를 사용하여 다음 명령을 실행하면 됩니다.composer require pusher/pusher-php-server
작성이 완료되면 Pusher를 라디오 드라이버로 사용하도록 Laravel을 설정해야 합니다. 이를 위해 Laravel 설치 루트 디렉터리에 있는 .env
파일을 열어 주십시오.다음 구성에 맞게 값을 업데이트합니다.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
Important Note: If you’re using the EU or AP Cluster, make sure to update the options array in your
config/broadcasting.php
config since Laravel defaults to using the US Server. You can use all the options the Pusher PHP Library supports.
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이 프로필에 설정한 모든 드라이버를 사용하여 이 이벤트를 방송해야 한다는 것을 알려준다.우리는 두 개의 매개 변수, 사용자 이름과 동사를 받아들이는 구조 함수가 하나 더 있다.우리는 잠시 후에 이 문제를 계속 토론할 것이다.우리는 이 변수들을 같은 방식으로 명명된 클래스 속성에 분배할 것이다.중요한 것은 대중에게 이 부동산들을 보여주는 것이다.이렇게 하지 않으면 이 속성은 무시됩니다.
마지막으로, 우리는 방송할 채널의 이름을 설정합니다.
응용 프로그램 보기 만들기
우리는 그것의 단순성을 유지하고 알림 아이콘이 있는 내비게이션 표시줄을 볼 수 있는 보기를 만들 것입니다.새 알림을 사용할 수 있으면 페이지를 새로 고칠 필요 없이 아이콘이 업데이트됩니다.디자인을 통해 본 강좌의 통지는 짧다.원하는 경우 이 기능을 확장하고 페이지를 다시 불러온 후 더 오래 지속할 수 있습니다.
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>
이것은 주로 많은 유도 소음이기 때문에 우리는 중요한 부분을 격리할 것이다. 주로 Javascript이다.우리는 Pusher javascript library을 포함하고 자바스크립트 블록을 추가하여 이 신기한 기능을 실현했다.자바스크립트 블록의 일부 부분을 봅시다.// 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...
});
PROTIP: By default, Laravel will broadcast the event using the event’s class name. However, you may customize the broadcast name by defining a broadcastAs method on the event:
public function broadcastAs() {
return ‘event-name’;
}
위의 코드는 Pusher JS 라이브러리를 초기화하고 채널을 구독하는 것입니다.그리고 이 채널에서 방송된 이벤트를 수신할 때 호출되도록 리셋합니다.
설정 테스트
마지막으로, 우리의 설정을 테스트하기 위해서, 우리는 수동으로 이벤트를 호출하는 루트를 만들 것입니다.만약 모든 것이 예상대로 진행된다면, 우리는 언제든지 노선에 도착할 때 새로운 통지를 받을 것이다.새로운 노선을 추가하겠습니다.
Route::get('test', function () {
event(new App\Events\StatusLiked('Someone'));
return "Event has been sent!";
});
이제 Laravel을 사용하여 PHP 서버를 시작할 수 있습니다. 그러면 코드가 유효한지 테스트할 수 있습니다.$ php artisan serve
결론
본고에서 우리는 Pusher의 강력한 기능을 이용하여 현대 웹 알림 시스템을 만들 수 있는데 이것은 매우 간단하다.이것은 단지 Pusher를 사용하여 진정으로 할 수 있는 일에 대한 초보적인 이해일 뿐이다.이 예는 단지 너에게 가능성을 보여 주었을 뿐이다.
코드는 GitHub 에서 찾을 수 있습니다. 이 코드를 사용하면 시작, 갈라짐, 게임을 할 수 있습니다.Laravel과 Pusher는 어떻게 사용하시겠습니까?너는 어떤 고급 용례도 생각해 낼 수 있니?얘네 뭐야?댓글로 알려주세요!
이 박문은 처음으로 PusherBlog에 등장했다
Reference
이 문제에 관하여(Laravel과 Pusher를 사용하여 웹 기반 알림을 만드는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/neo/how-to-create-web-notifications-using-laravel-and-pusher-3b81텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)