<?php
namespace App\Event;
use Cake\Event\EventListenerInterface;
use Notifier\Utility\NotificationManager;
class FeedbackListener implements EventListenerInterface {
public function implementedEvents() {
return [
'Model.afterSave' => 'addFeedbackNotification',
];
}
public function addFeedbackNotification($event, $entity) {
if ($entity->source() == 'AkkaFeedback.Feedbacks' && $entity->isNew()) {
// Add notification
$notificationManager = NotificationManager::instance();
$notificationManager->addTemplate('newMessage', [
'title' => 'New Message Notification',
'body' => 'New message from :name'
]);
$notificationManager->addRecipientList('administrators', [7]);
$notificationManager->notify([
'recipientLists' => ['administrators'],
'template' => 'newMessage',
'vars' => [
'id' => $entity->get('id'),
'name' => $entity->get('name'),
'feedback' => $entity->get('feedback')
]
]);
}
}
}
bootstrap.php
/**
* Event listeners
*/
use App\Event\FeedbackListener;
use Cake\Event\EventManager;
$feedackListener = new FeedbackListener();
EventManager::instance()->attach($feedackListener);
Model.afterSave
. So, on every model's safe you'll fire this event (thats why you used if/else
). So to improve your code I would suggest creating a new event into your afterSave
-method in your model (in the plugin), and listen on that event. The bootstrap looks good!
afterSave
to my plugin to make it easy to track its save events. The reason I went this route is because I use a plugin from another developer that does not fire any specific events and I wanted a notification on new creation as well. But all good for now, thanks for the help!
Oh, to improve your code, I would move
$notificationManager->addTemplate('newMessage', [
'title' => 'New Message Notification',
'body' => 'New message from :name'
]);
to your bootstrap.php
. Else the templates can't be read when showing them...
jQuery.noConflict();
var interval = 1000;
setTimeout(checkStatus, interval);
function checkStatus(){
jQuery.ajax({
method: "GET",
url: '/dashboard/notifications/new'
}).done(function(data){
notifications = jQuery.parseJSON(data);
notificationsUpdate(notifications);
});
// ie. every 1, 2, 3, 4, 5, 6, 7 secs, etc
interval += 1000;
// ie. double - every 1, 2, 4, 8, 16, 32 secs, etc.
// interval = interval * 2;
setTimeout(checkStatus, interval);
}
function notificationsUpdate(notifications){
// Code to handle notifications display
}