Mysql
 SQL >> Database >  >> RDS >> Mysql

Sistema di notifiche con PHP e MySQL

Questa domanda ha ormai 9 mesi, quindi non so se l'autore abbia ancora bisogno di una risposta ma, viste le numerose visualizzazioni e l'interessante ricompensa, vorrei aggiungere anche il mio contributo.

In questo post cercherò di fornire un esempio semplice e ben spiegato su come iniziare a costruire un sistema di notifiche.

Modifica: ok, alla fine è venuto molto, molto, molto più lungo di quanto mi aspettassi. Verso la fine ero davvero esausto, mi dispiace.

WTLDR (versione brevissima)

Domanda 1: avere un flag su ogni notifica.

Domanda 2: continuare a memorizzare ogni notifica come singolo record nel database e raggrupparle al momento della richiesta.

Struttura

Assumo che le notifiche appaiano più o meno così:

+---------------------------------------------+ | ▣ James has uploaded new Homework: Math 1+1 | +---------------------------------------------+ | ▣ Jane and John liked your comment: Im s... | +---------------------------------------------+ | ▢ The School is closed on independence day. | +---------------------------------------------+ 

Dietro le quinte, i dati potrebbero assomigliare a questo:

+--------+-----------+--------+-----------------+-------------------------------------------+ | unread | recipient | sender | type | reference | +--------+-----------+--------+-----------------+-------------------------------------------+ | true | me | James | homework.create | Math 1 + 1 | +--------+-----------+--------+-----------------+-------------------------------------------+ | true | me | Jane | comment.like | Im sick of school | +--------+-----------+--------+-----------------+-------------------------------------------+ | true | me | John | comment.like | Im sick of school | +--------+-----------+--------+-----------------+-------------------------------------------+ | false | me | system | message | The School is closed on independence day. | +--------+-----------+--------+-----------------+-------------------------------------------+ 

Nota: non consiglio di raggruppare le notifiche all'interno del database; farlo a runtime mantiene tutto molto più flessibile.

  • Unread (da leggere)
    Ogni notifica dovrebbe avere un flag che indica se il destinatario l'ha già aperta.
  • Recipient (destinatario)
    Definisce chi riceve la notifica.
  • Sender (mittente)
    Definisce chi ha generato la notifica.
  • Type (tipo)
    Invece di salvare ogni messaggio in testo libero nel database, crea dei tipi. In questo modo puoi predisporre gestori specifici per i diversi tipi di notifica nel backend. Riduce la quantità di dati memorizzati e offre maggiore flessibilità, come la traduzione delle notifiche e la modifica di messaggi passati.
  • Reference (riferimento)
    La maggior parte delle notifiche avrà un riferimento a un record del database o dell'applicazione.

In tutti i sistemi su cui ho lavorato c'era una relazione di riferimento 1 a 1 per le notifiche; potresti avere una relazione 1 a n, ma continuerò l'esempio con 1:1. Questo significa anche che non serve un campo che definisca il tipo di oggetto riferito, perché è determinato dal tipo di notifica.

Tabella SQL

Definendo una vera struttura di tabella in SQL arriviamo ad alcune decisioni di design. Userò la soluzione più semplice, più o meno questa:

+--------------+--------+---------------------------------------------------------+ | column | type | description | +--------------+--------+---------------------------------------------------------+ | id | int | Primary key | +--------------+--------+---------------------------------------------------------+ | recipient_id | int | The receivers user id. | +--------------+--------+---------------------------------------------------------+ | sender_id | int | The sender's user id. | +--------------+--------+---------------------------------------------------------+ | unread | bool | Flag if the recipient has already read the notification | +--------------+--------+---------------------------------------------------------+ | type | string | The notification type. | +--------------+--------+---------------------------------------------------------+ | parameters | array | Additional data to render different notification types. | +--------------+--------+---------------------------------------------------------+ | reference_id | int | The primary key of the referencing object. | +--------------+--------+---------------------------------------------------------+ | created_at | int | Timestamp of the notification creation date. | +--------------+--------+---------------------------------------------------------+ 

Oppure, per i più pigri, il comando SQL di creazione della tabella per questo esempio:

CREATE TABLE `notifications` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `recipient_id` int(11) NOT NULL, `sender_id` int(11) NOT NULL, `unread` tinyint(1) NOT NULL DEFAULT '1', `type` varchar(255) NOT NULL DEFAULT '', `parameters` text NOT NULL, `reference_id` int(11) NOT NULL, `created_at` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

Servizio PHP

Questa implementazione dipende completamente dalle esigenze della tua applicazione. Nota: è solo un esempio, non lo standard aureo per costruire un sistema di notifiche in PHP.

Modello Notification

Questo è un modello base di esempio della notifica: niente di elaborato, solo le proprietà necessarie e i metodi astratti messageForNotification e messageForNotifications, che ci aspettiamo vengano implementati nei diversi tipi di notifica.

abstract class Notification { protected $recipient; protected $sender; protected $unread; protected $type; protected $parameters; protected $referenceId; protected $createdAt; /** * Message generators that have to be defined in subclasses */ public function messageForNotification(Notification $notification) : string; public function messageForNotifications(array $notifications) : string; /** * Generate message of the current notification. */ public function message() : string { return $this->messageForNotification($this); } } 

Dovrai aggiungere tu il costruttore, i getter, i setter e simili secondo il tuo stile: non fornirò un sistema di notifiche pronto all'uso.

Tipi di notifica

Ora puoi creare una sottoclasse Notification per ogni tipo. Il seguente esempio gestisce l'azione "like" di un commento:

  • Ray ha messo like al tuo commento. (1 notifica)
  • John e Jane hanno messo like al tuo commento. (2 notifiche)
  • Jane, Johnny, James e Jenny hanno messo like al tuo commento. (4 notifiche)
  • Jonny, James e altri 12 hanno messo like al tuo commento. (14 notifiche)

Esempio di implementazione:

namespace Notification\Comment; class CommentLikedNotification extends \Notification { /** * Generate a message for a single notification * * @param Notification $notification * @return string */ public function messageForNotification(Notification $notification) : string { return $this->sender->getName() . 'has liked your comment: ' . substr($this->reference->text, 0, 10) . '...'; } /** * Generate a message for a multiple notifications * * @param array $notifications * @return string */ public function messageForNotifications(array $notifications, int $realCount = 0) : string { if ($realCount === 0) { $realCount = count($notifications); } // when there are two if ($realCount === 2) { $names = $this->messageForTwoNotifications($notifications); } // less than five elseif ($realCount < 5) { $names = $this->messageForManyNotifications($notifications); } // to many else { $names = $this->messageForManyManyNotifications($notifications, $realCount); } return $names . ' liked your comment: ' . substr($this->reference->text, 0, 10) . '...'; } /** * Generate a message for two notifications * * John and Jane has liked your comment. * * @param array $notifications * @return string */ protected function messageForTwoNotifications(array $notifications) : string { list($first, $second) = $notifications; return $first->getName() . ' and ' . $second->getName(); // John and Jane } /** * Generate a message many notifications * * Jane, Johnny, James and Jenny has liked your comment. * * @param array $notifications * @return string */ protected function messageForManyNotifications(array $notifications) : string { $last = array_pop($notifications); foreach($notifications as $notification) { $names .= $notification->getName() . ', '; } return substr($names, 0, -2) . ' and ' . $last->getName(); // Jane, Johnny, James and Jenny } /** * Generate a message for many many notifications * * Jonny, James and 12 other have liked your comment. * * @param array $notifications * @return string */ protected function messageForManyManyNotifications(array $notifications, int $realCount) : string { list($first, $second) = array_slice($notifications, 0, 2); return $first->getName() . ', ' . $second->getName() . ' and ' . $realCount . ' others'; // Jonny, James and 12 other } } 

Gestore delle notifiche

Per lavorare con le notifiche nella tua applicazione, crea qualcosa di simile a un notification manager:

class NotificationManager { protected $notificationAdapter; public function add(Notification $notification); public function markRead(array $notifications); public function get(User $user, $limit = 20, $offset = 0) : array; } 

La proprietà notificationAdapter dovrebbe contenere la logica di comunicazione diretta con il backend dati, in questo caso MySQL.

Creazione delle notifiche

Usare i trigger mysql non è sbagliato, perché non esiste una soluzione sbagliata in assoluto. Ciò che funziona, funziona. Ma consiglio strongly di non lasciare che sia il database a gestire la logica dell'applicazione.

Quindi, all'interno del notification manager, potresti fare qualcosa del genere:

public function add(Notification $notification) { // only save the notification if no possible duplicate is found. if (!$this->notificationAdapter->isDoublicate($notification)) { $this->notificationAdapter->add([ 'recipient_id' => $notification->recipient->getId(), 'sender_id' => $notification->sender->getId() 'unread' => 1, 'type' => $notification->type, 'parameters' => $notification->parameters, 'reference_id' => $notification->reference->getId(), 'created_at' => time(), ]); } } 

Dietro il metodo add del notificationAdapter può esserci un semplice comando INSERT MySQL. Usare questa astrazione ad adapter ti permette di passare facilmente da MySQL a un database documentale come mongodb, scelta sensata per un sistema di notifiche.

Il metodo isDoublicate del notificationAdapter dovrebbe semplicemente verificare se esiste già una notifica con lo stesso recipient, sender, type e reference.

Non lo ripeterò mai abbastanza: questo è solo un esempio.

Supponiamo quindi di avere una sorta di controller con un'action per quando un insegnante carica un compito:

function uploadHomeworkAction(Request $request) { // handle the homework and have it stored in the var $homework. // how you handle your services is up to you... $notificationManager = new NotificationManager; foreach($homework->teacher->students as $student) { $notification = new Notification\Homework\HomeworkUploadedNotification; $notification->sender = $homework->teacher; $notification->recipient = $student; $notification->reference = $homework; // send the notification $notificationManager->add($notification); } } 

Verrà creata una notifica per ogni studente dell'insegnante quando questi carica un nuovo compito.

Lettura delle notifiche

Ora arriva la parte difficile. Il problema del raggruppamento lato PHP è che devi caricare tutte le notifiche dell'utente corrente per raggrupparle correttamente. Con pochi utenti probabilmente non è un problema, ma ciò non lo rende una buona pratica.

La soluzione semplice è limitare il numero di notifiche richieste e raggruppare solo quelle. Funziona bene quando non ci sono molte notifiche simili (diciamo 3-4 su 20). Ma se il post di un utente riceve un centinaio di like e selezioni solo le ultime 20 notifiche, l'utente vedrà soltanto che 20 persone hanno messo like al suo post.

Una soluzione "corretta" sarebbe raggruppare le notifiche già nel database e selezionare solo alcuni campioni per gruppo, per poi iniettare il conteggio reale nei messaggi.

Ecco un rapido estratto:

select *, count(*) as count from notifications where recipient_id = 1 group by `type`, `reference_id` order by created_at desc, unread desc limit 20 

Ora sai quali notifiche dovrebbero comparire per l'utente e quante ne contiene ogni gruppo.

$notifcationGroups = []; foreach($results as $notification) { $notifcationGroup = ['count' => $notification['count']]; // when the group only contains one item we don't // have to select it's children if ($notification['count'] == 1) { $notifcationGroup['items'] = [$notification]; } else { // example with query builder $notifcationGroup['items'] = $this->select('notifications') ->where('recipient_id', $recipient_id) ->andWehere('type', $notification['type']) ->andWhere('reference_id', $notification['reference_id']) ->limit(5); } $notifcationGroups[] = $notifcationGroup; } 

Assumendo che il metodo get del notificationAdapter implementi questo raggruppamento e restituisca un array come questo:

[ { count: 12, items: [Note1, Note2, Note3, Note4, Note5] }, { count: 1, items: [Note1] }, { count: 3, items: [Note1, Note2, Note3] } ] 

Poiché abbiamo sempre almeno una notifica per gruppo e l'ordinamento privilegia le notifiche da leggere e nuove, possiamo usare la prima notifica come campione per il rendering.

class NotificationGroup { protected $notifications; protected $realCount; public function __construct(array $notifications, int $count) { $this->notifications = $notifications; $this->realCount = $count; } public function message() { return $this->notifications[0]->messageForNotifications($this->notifications, $this->realCount); } // forward all other calls to the first notification public function __call($method, $arguments) { return call_user_func_array([$this->notifications[0], $method], $arguments); } } 

Infine, il metodo get del NotificationManager potrebbe apparire così:

public function get(User $user, $limit = 20, $offset = 0) : array { $groups = []; foreach($this->notificationAdapter->get($user->getId(), $limit, $offset) as $group) { $groups[] = new NotificationGroup($group['notifications'], $group['count']); } return $groups; } 

E, per finire, dentro una possibile action del controller:

public function viewNotificationsAction(Request $request) { $notificationManager = new NotificationManager; foreach($notifications = $notificationManager->get($this->getUser()) as $group) { echo $group->unread . ' | ' . $group->message() . ' - ' . $group->createdAt() . "\n"; } // mark them as read $notificationManager->markRead($notifications); }