Notifiche
Flarum include un potente sistema di notifica per avvisare gli utenti di nuove attività.
Tipi di notifiche
Definizione di un tipo di notifica
To define a notification type, you will need to create a new class which implements Flarum\Notification\Blueprint\BlueprintInterface and Flarum\Notification\AlertableInterface. Questa classe definirà il contenuto e il comportamento della notifica tramite i seguenti metodi:
getSubject()Il modello su cui si riferisce la notifica (ad es.getSender()Il modelloUserper l'utente che ha attivato la notifica.getData()Qualsiasi altro dato che potresti voler includere per l'accesso sul frontend (es. Il vecchio titolo della discussione quando rinominato).getType()Qui è dove assegni il nome alla notifica, questo sarà importante per i passaggi successivi.getSubjectModel(): Specify the type of model the subject is (fromgetSubject).
Diamo un'occhiata a un esempio tratto da Flarum Likes:
<?php
namespace Flarum\Likes\Notification;
use Flarum\Notification\AlertableInterface;
use Flarum\Notification\Blueprint\BlueprintInterface;
use Flarum\Post\Post;
use Flarum\User\User;
class PostLikedBlueprint implements BlueprintInterface, AlertableInterface
{
public $post;
public $user;
public function __construct(Post $post, User $user)
{
$this->post = $post;
$this->user = $user;
}
public function getSubject()
{
return $this->post;
}
public function getFromUser()
{
return $this->user;
}
public function getData()
{
}
public static function getType()
{
return 'postLiked';
}
public static function getSubjectModel()
{
return Post::class;
}
}
Take a look at DiscussionRenamedBlueprint if you want another example.
Registrazione di un tipo di notifica
Quindi, registriamo la tua notifica in modo che Flarum lo sappia. Ciò consentirà agli utenti di modificare il modo in cui desiderano ricevere l'avviso della notifica.
Possiamo farlo con il metodo type dell'extender Notification
$blueprint: La tua classe statica (esempio:PostLikedBlueprint::class)$enabledByDefault: Qui è dove imposti i metodi di notifica che saranno abilitati per impostazione predefinita. Accetta una serie di stringhe, include "alert" per avere notifiche del forum (l'icona della campana), include "email" per le notifiche email. Puoi usarne uno entrambi o nessuno! (esempio:['alert']imposterebbe solo le notifiche nel forum per impostazione predefinita)
Vediamo un esempio da Flarum Subscriptions:
<?php
use Flarum\Extend
use Flarum\Subscriptions\Notification\NewPostBlueprint;
return [
// Other extenders
(new Extend\Notification())
->type(NewPostBlueprint::class, ['alert', 'email']),
// Other extenders
];
La tua notifica sta venendo davvero bene! Rimangono solo poche cose da fare!
Notifiche spedibili
Oltre a registrare la nostra notifica da inviare via e-mail, se vogliamo effettivamente inviarla, dobbiamo fornire un po 'più di informazioni: vale a dire, il codice per generare l'oggetto e il corpo dell'e-mail.
A tale scopo, è necessario implementare Flarum\Notification\MailableInterface in aggiunta a Flarum\Notification\Blueprint\BlueprintInterface. Questo viene fornito con 2 metodi aggiuntivi:
Questo viene fornito con 2 metodi aggiuntivi:
getEmailViews()should return an array of email types (bothtextandhtml) to Blade View names. I namespace per queste devono prima essere registrati. Questi poi verranno utilizzati per generare il corpo dell'email.getEmailSubject(TranslatorInterface $translator)dovrebbe restituire una stringa per l'oggetto dell'email. Viene passata un'istanza del traduttore per abilitare le e-mail di notifica tradotte.
Diamo un'occhiata a un esempio tratto da Menzioni di Flarum
<?php
namespace Flarum\Mentions\Notification;
use Flarum\Database\AbstractModel;
use Flarum\Notification\AlertableInterface;
use Flarum\Notification\Blueprint\BlueprintInterface;
use Flarum\Notification\MailableInterface;
use Flarum\Post\Post;
use Flarum\User\User;
use Symfony\Contracts\Translation\TranslatorInterface;
class PostMentionedBlueprint implements BlueprintInterface, AlertableInterface, MailableInterface
{
public function __construct(
public Post $post,
public Post $reply
) {
}
public function getSubject(): ?AbstractModel
{
return $this->post;
}
public function getFromUser(): ?User
{
return $this->reply->user;
}
public function getData(): mixed
{
return ['replyNumber' => (int) $this->reply->number];
}
public function getEmailViews(): array
{
return [
'text' => 'flarum-mentions::emails.plain.postMentioned',
'html' => 'flarum-mentions::emails.html.postMentioned',
];
}
public function getEmailSubject(TranslatorInterface $translator): string
{
return $translator->trans('flarum-mentions.email.post_mentioned.subject', [
'{replier_display_name}' => $this->post->user->display_name,
'{title}' => $this->post->discussion->title
]);
}
public static function getType(): string
{
return 'postMentioned';
}
public static function getSubjectModel(): string
{
return Post::class;
}
}
If you need your notification to be sent by email only, you can remove the AlertableInterface implementation, which will skip sending an alert for that notification.
Mail Templates
Now that we have our email views registered, we need to create the actual email templates. These are Blade views, and should be placed in the views/emails directory of your extension (unless you registered a different path). The filenames should match the names you returned in getEmailViews.
You can use the following blade components:
mail::html.notification: The HTML template for notification emails. Use this when your notification is a type that can be disabled by the user, as it includes an unsubscribe link.mail::plain.notification: The plain text template for notification emails. Use this when your notification is a type that can be disabled by the user, as it includes an unsubscribe link.mail::html.information: The HTML template for informational emails. Use this when your notification is a type that cannot be disabled by the user. For example, the suspensions extension uses this for suspension emails.mail::plain.information: The plain text template for informational emails. Use this when your notification is a type that cannot be disabled by the user. For example, the suspensions extension uses this for suspension emails.
Driver di notifica
Oltre a registrare i tipi di notifica, possiamo anche aggiungere nuovi driver accanto a quelli predefiniti alert e email.
Il driver dovrebbe implementare Flarum\Notification\Driver\NotificationDriverInterface. Diamo un'occhiata a un esempio annotato dall'estensione Pusher:
<?php
namespace Flarum\Pusher;
use Flarum\Notification\Blueprint\BlueprintInterface;
use Flarum\Notification\Driver\NotificationDriverInterface;
use Illuminate\Contracts\Queue\Queue;
class PusherNotificationDriver implements NotificationDriverInterface
{
/**
* @var Queue
*/
protected $queue;
public function __construct(Queue $queue)
{
$this->queue = $queue;
}
/**
* {@inheritDoc}
*/
public function send(BlueprintInterface $blueprint, array $users): void
{
// The `send` method is responsible for determining any notifications need to be sent.
// If not (for example, if there are no users to send to), there's no point in scheduling a job.
// Consigliamo ALTAMENTE che le notifiche vengano inviate tramite una coda per motivi di prestazioni.
if (count($users)) {
$this->queue->push(new SendPusherNotificationsJob($blueprint, $users));
}
}
/**
* {@inheritDoc}
*/
public function registerType(string $blueprintClass, array $driversEnabledByDefault): void
{
// Questo metodo è generalmente utilizzato per registrare una preferenza utente per questa notifica.
// Nel caso di Pusher, non ce n'è bisogno.
}
}
Anche i driver di notifica vengono registrati tramite l'extender Notification, usando il metodo driver. Vengono forniti i seguenti argomenti
$driverName: Un nome unico e leggibile per il driver$driverClass: The class static of the driver (example:Driver::class)$typesEnabledByDefault: Un array di tipi per i quali questo driver dovrebbe essere abilitato per impostazione predefinita. Questo verrà utilizzato nel calcolo$driversEnabledByDefault, che viene fornito dal metodoregisterTypedel driver.
Un altro esempio da Flarum Pusher:
<?php
use Flarum\Extend
use Flarum\Pusher\PusherNotificationDriver;
return [
// Other extenders
(new Extend\Notification())
->driver('pusher', PusherNotificationDriver::class),
// Other extenders
];
Notifiche di rendering
Come per tutto in Flarum, ciò che registriamo nel backend, deve essere registrato anche nel frontend
Come per i progetti di notifica, dobbiamo dire a Flarum come vogliamo che venga visualizzata la nostra notifica.
Innanzitutto, crea una classe che estenda il componente di notifica. Quindi, ci sono 4 funzioni da aggiungere:
icon(): Le icone Font Awesome che appariranno accanto al testo della notifica (esempio:fas fa-code-branch).href(): Il collegamento che dovrebbe essere aperto quando si fa clic sulla notifica (esempio:app.route.post(this.attrs.notification.subject())).content(): Cosa dovrebbe mostrare la notifica stessa. Dovrebbe dire il nome utente e quindi l'azione. Sarà seguito da quando è stata inviata la notifica (assicurati di utilizzare le traduzioni).excerpt(): A little excerpt that is shown below the notification (commonly an excerpt of a post).
Diamo un'occhiata al nostro esempio, vero?
From Flarum Subscriptions, when a new post is posted on a followed discussion:
import Notification from 'flarum/components/Notification';
import username from 'flarum/helpers/username';
export default class NewPostNotification extends Notification {
icon() {
return 'fas fa-star';
}
href() {
const notification = this.attrs.notification;
const discussion = notification.subject();
const content = notification.content() || {};
return app.route.discussion(discussion, content.postNumber);
}
content() {
return app.translator.trans('flarum-subscriptions.forum.notifications.new_post_text', {user: this.attrs.notification.sender()});
}
}
In the example, the icon is a star, the link will go to the new post, and the content will say that "{user} posted".
Successivamente, dobbiamo dire a Flarum che la notifica che invii nel backend corrisponde alla notifica frontend che abbiamo appena creato.
Apri il tuo index.js (quello del forum) e inizia importando il modello di notifica appena creato. Quindi aggiungi la seguente riga:
app.notificationComponents.{nameOfNotification} = {NotificationTemplate};
Assicurati di sostituire {nameOfNotification}con il nome della notifica nel tuo progetto PHP (getType()) e sostituisci {NotificationTemplate} con il nome del modello di notifica JS che abbiamo appena creato! (Assicurati che sia importato!)
If the subject of your notification is a new model, make sure you have a frontend represantation of it registered in the frontend store. Read more about it here
Diamo agli utenti un'opzione per modificare le loro impostazioni per la tua notifica. All you have to do is extend the notificationGrid's notificationTypes() function
From Flarum-Likes:
import { extend } from 'flarum/extend';
import app from 'flarum/app';
import NotificationGrid from 'flarum/components/NotificationGrid';
import PostLikedNotification from './components/PostLikedNotification';
app.initializers.add('flarum-likes', () => {
app.notificationComponents.postLiked = PostLikedNotification;
extend(NotificationGrid.prototype, 'notificationTypes', function (items) {
items.add('postLiked', {
name: 'postLiked',
icon: 'far fa-thumbs-up',
label: app.translator.trans('flarum-likes.forum.settings.notify_post_liked_label')
});
});
});
Aggiungi semplicemente il nome della tua notifica (dal progetto), un'icona che desideri mostrare e una descrizione della notifica e il gioco è fatto!
Inviare Notifiche
I dati non appaiono solo magicamente nel database
Ora che hai configurato la tua notifica, è il momento di inviarla all'utente!
Thankfully, this is the easiest part, simply useNotificationSyncer's sync function. Accetta due argomenti:
BlueprintInterface: This is the blueprint to be instantiated we made in the first step, you must include all variables that are used on the blueprint (example: if a user likes a post you must include theusermodel that liked the post).$users: Questo accetta un array diuserche dovrebbe ricevere la notifica
*Che cos'è? Vuoi essere in grado di eliminare anche le notifiche? * Il modo più semplice per rimuovere una notifica è passare esattamente gli stessi dati dell'invio di una notifica, tranne che con un array vuoto di destinatari.
Diamo un'occhiata al nostro ** ultimo ** esempio di oggi:
Da Flarum Likes:
<?php
namespace Flarum\Likes\Listener;
use Flarum\Likes\Event\PostWasLiked;
use Flarum\Likes\Event\PostWasUnliked;
use Flarum\Likes\Notification\PostLikedBlueprint;
use Flarum\Notification\NotificationSyncer;
use Flarum\Post\Post;
use Flarum\User\User;
use Illuminate\Contracts\Events\Dispatcher;
class SendNotificationWhenPostIsLiked
{
protected $notifications;
public function __construct(NotificationSyncer $notifications)
{
$this->notifications = $notifications;
}
public function subscribe(Dispatcher $events)
{
$events->listen(PostWasLiked::class, [$this, 'whenPostWasLiked']);
$events->listen(PostWasUnliked::class, [$this, 'whenPostWasUnliked']);
}
public function whenPostWasLiked(PostWasLiked $event)
{
$this->syncNotification($event->post, $event->user, [$event->post->user]);
}
public function whenPostWasUnliked(PostWasUnliked $event)
{
$this->syncNotification($event->post, $event->user, []);
}
public function syncNotification(Post $post, User $user, array $recipients)
{
if ($post->user->id != $user->id) {
$this->notifications->sync(
new PostLikedBlueprint($post, $user),
$recipients
);
}
}
}
Fantastico! Ora puoi spammare gli utenti con aggiornamenti sugli eventi del forum!
Provato tutto? Beh, se hai provato tutto allora indovino... Scherzo. Sentiti libero di postare nella Community di Flarum o su Discord e qualcuno ti darà una mano.