I wrote a forum app sometimes ago and am trying to improve it . I have an issue that is hard for me to solve(I don’t even know how to solve it, I just have the idea), how can I create a notification menu like the one on this site, stackoverflow etc that display at the top of the menu for a user about messages that were received on thread or post he start or comment on.
Hi there, here’s a basic class I have written in 5 minutes just for you
Please note I have not tested it but it should give you an idea and set you in the right direction. If you have any questions please ask:
<?php
class Notifications
{
public function __construct(string $id)
{
$this->id = $id;
if(session_id() == '' || !isset($_SESSION)) {
session_start();
}
}
public function getMessages() {
if (!empty($_SESSION['notifications'][$this->id])) {
return $_SESSION['notifications'][$this->id];
}
return [];
}
public function render() {
$rv = "<ul id='$this->id-notifications' class='notifications'>";
foreach ($this->getMessages() as $message) {
$rv .= $this->renderMessage($message);
}
$rv.= "</ul>";
return $rv;
}
public function renderMessage(array $message) {
$type = $message['type'] ?? 'info';
if (empty($message['text'])) {
return;
}
$rv .= "<li class='message $type-message'>";
$rv .= $message['text'];
$rv .= "</li>";
return $rv;
}
public function addMessage(string $text, string $type) {
$_SESSION['notifications'][$this->id][] = [
'text' => $text,
'type' => $type
];
}
public static function addMessageStatic(string $text, string $type, string $notificationsId) {
$_SESSION['notifications'][$notificationsId][] = [
'text' => $text,
'type' => $type
];
}
}
$notifications = new Notifications('myNotifications');
$notifications->addMessage('Hello World!');
Notifications::addMessageStatic("Hello World, I cannot reach the instance of my class but I know the id!", 'info', 'myNotifications');
echo $notifications->render();