A very lightweight library to handle notifications the smart way.

Overview

NAMSHI | Notificator

Build Status

SensioLabsInsight

Notificator is a very simple and lightweight library to handle notifications the smart way.

It took inspiration from other libraries and patterns (Monolog and event dispatching) in order to provide a domain-driven lean notification library.

Concepts are very simple: you have a notification Manager which has a few handlers registered with it (maybe an Email handler, a Skype handler, etc.); you only have to create a notification class, define which handlers should handle it and trigger it through the manager.

It is way simpler in code than in words, check the documentation below!

Installation

Installation can be done via composer, as the library is already on packagist.

The library uses semantic versioning for its API, so it is recommended to use a stable minor version (1.0, 1.1, etc.) and stick to it when declaring dependencies through composer:

"namshi/notificator": "1.0.*",

Usage

Using this library is very easy thanks to the simple concept - borrowed from others - behind it: you basically have a notification manager with some handlers and then you fire (trigger()) the notification with the manager. At that point, all the handlers that need to fire that notification will take care of firing it in their context (might be an email, a skype message, etc) and tell the manager that they're done, so that the manager can forward the notification to the next handler.

<?php

// import namespaces
use Namshi\Notificator\Notification\Handler\NotifySend as NotifySendHandler;
use Namshi\Notificator\Manager;
use Namshi\Notificator\Notification\NotifySend\NotifySendNotification;

//  create the handler
$handler = new NotifySendHandler();

// create the manager and assign the handler to it
$manager = new Manager();
$manager->addHandler($handler);

$notification = new NotifySendNotification("...whatever message...");

//  trigger the notification
$manager->trigger($notification);

This code, ran on ubuntu, will fire the notification using the notify-send utility:

notify-send

The notification Manager

The manager is the entity that registers all the handlers and fires the notification.

You can set and add handlers very easily:

<?php

$handler  = new MyHandler();
$handlers = array(
    new AnotherHandler(), new AnotherOneHandler(),
);

$manager = new Manager();

// add multiple handlers
$manager->setHandlers($handlers);

// add a single handler
$manager->addHandler($handler);

// reset the handlers
$manager->setHandlers(array());

Creating a new notification

Creating new notifications is very easy, as they are plain PHP classes.

They might extend the base Notification class but that is not mandatory. It is recommended, to be able to fire one notification through multiple handlers, to extend the base Notification class, and implement different interfaces that will be later checked by the handlers.

<?php

use Namshi\Notificator\Notification;
use Namshi\Notificator\NotificationInterface;

interface EchoedNotificationInterface extends NotificationInterface
{
    public function getMessage();
}

interface EmailNotificationInterface extends NotificationInterface
{
    public function getAddress();
    public function getSubject();
    public function getBody();
}

class DoubleNotification extends Notification implements EchoedNotificationInterface, EmailNotificationInterface
{
    protected $address;
    protected $body;
    protected $subject;

    public function __construct($address, $subject, $body, array $parameters = array())
    {
        parent::__construct($parameters);

        $this->address  = $address;
        $this->body     = $body;
        $this->subject  = $subject;
        $this->message  = $body;
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function getSubject()
    {
        return $this->subject;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function getMessage()
    {
        return $this->message;
    }
}

As you probably got, the above notification class is meant to be triggered via email and with the echo function (pretty useless, but gives you an idea).

But the work wouldn't be over here, as you would need to implement handlers for this notification...

Creating a new handler

Let's say that we want to create the handlers that would handle the notification above, by echoing it and sending it via email: it is a matter of implementing 2 classes with a couple methods, shouldHandle and handle.

Let's see how the EchoedNotificationHandler should look like:

use Namshi\Notificator\Notification\Handler\HandlerInterface;
use Namshi\Notificator\NotificationInterface;

class EchoedNotificationHandler implements HandlerInterface
{
    public function shouldHandle(NotificationInterface $notification)
    {
        return $notification instanceOf EchoedNotificationInterface;
    }

    public function handle(NotificationInterface $notification)
    {
        echo $notification->getMessage();
    }
}

Pretty easy, right?

First, we need to check if this handler is handling the given notification, and that check is done by seeing if the notification implements a known interface; second, we actually trigger the notification.

The same thing needs to be done for the EmailNotificationHandler:

use Namshi\Notificator\Notification\Handler\HandlerInterface;
use Namshi\Notificator\NotificationInterface;

class EmailNotificationHandler implements HandlerInterface
{
    public function shouldHandle(NotificationInterface $notification)
    {
        return $notification instanceOf EmailNotificationInterface;
    }

    public function handle(NotificationInterface $notification)
    {
        mail($notification->getAddress(), $notification->getSubject(), $notification->getBody());
    }
}

If you want to stop notification propagation after an handler has triggered the notification, you just need to return false in the handle method of the handler:

public function handle(NotificationInterface $notification)
{
    // do whatever you want with the notification
    // ...

    return false;
}

This will tell the manager to stop propagating the notification to other handlers.

Inside Symfony2

Namshi is currently using this library inside their Symfony2 applications.

Add the bundle to your AppKernel.php:

     $bundles = array(
         ...
         new Namshi\Notificator\Symfony\NamshiNotificatorBundle()
     );

To register a new handler, create a service with the notification.handler tag:

namshi.notification.handler.email:
    class: Namshi\Notificator\Notification\Handler\Emailvision
    arguments:
      client: @namshi.email_client.emailvision
            
    tags:
        - { name: notification.handler }

namshi.email_client.emailvision:
    class: Namshi\Emailvision\Client
    arguments:
      config:
        test_email:
          random:   AAA
          encrypt:  BBB
          uidkey:   email
          stype:    NOTHING

This configuration registers an Emailvision handler.

RabbitMQ

If you use Symfony2 and the RabbitMQBundle you can trigger notifications with this library via RabbitMQ, by using the provided consumer.

Declare the consumer as a service:

namshi.notification.consumer:
    class: Namshi\Notificator\Messaging\RabbitMQ\Symfony2\Consumer
    arguments: [@namshi.notification.manager]

Then configure it within the RabbitMQ bundle:

old_sound_rabbit_mq:
    consumers:
        notification:
            connection: default
            exchange_options: {name: 'notifications', type: direct}
            queue_options:    {name: 'notifications'}
            callback:         namshi.notification.consumer

And at that point you can run the consumer with:

php app/console rabbitmq:consumer -w notification

To send notifications, the idea is that you serialize them inside the RabbitMQ messages:

$publisher = $container->get('old_sound_rabbit_mq.notifications_producer');

$notification = new MyWhateverNotification("man, this comes from RabbitMQ and Symfony2!");

$publisher->publish(serialize($notification));

That's it!

Built-in handlers

We, at Namshi have developed some very simple, built-in, handlers according to our needs. Keep in mind that the main reason behind building this kind of library is the ability of triggering notification from each component of our SOA, mostly via RabbitMQ.

You can take advantage of the following handlers:

  • SwiftMailer, which lets you use the amazing SwiftMailer to send email notifications through any SMTP server (ie. Amazon's SES, or SendGrid)
  • HipChat, which posts messages in an HipChat room
  • Emailvision, which sends emails through the Emailvision API
  • NotifySend, which triggers notifications on Ubuntu
  • RabbitMQ, which triggers notifications through RabbitMQ

If you have an idea for a new handler, don't hesitate with a pull request: sure, they can be implemented within your own code, but why not sharing them with the OSS ecosystem?

Examples

You can have a look at the few examples provided so far, under the examples directory:

Running specs

In order to run the spec suite after running composer install do the following:

php vendor/bin/phpspec run --format=dot
Comments
  • Fix handling of multi-word message

    Fix handling of multi-word message

    In my case (Ubuntu), I ran into a problem where the message passed had multiple words and notify-send threw "Invalid number of options" error ... the solution was to put "" around the message.

    opened by ipeevski 3
  • Notify-send class not using parameters

    Notify-send class not using parameters

    The class NotifySend is not making use of the parameters array inside the notification class.

    Example:

     $notification = new Namshi\Notificator\Notification(
                '"Codeception Tests results"',
                [
                    '--urgency' => 'low',
                    '--category' => 'testing',
                    '--icon' => $icon
                ]
            );
    

    The notify send command is outputed as:

    notify-send "Cododeception Test results"
    

    Making the following modification makes the command to accept the parameters inside Namshi\Notificator\Notification\Handler\NotifySend:

    protected function getCommand(NotifySendNotificationInterface $notification)
        {
            $command = "";
            if (count($notification->getParameters()) > 0) {
                foreach ($notification->getParameters() as $key => $value) {
                    $command .= " ";
                    $command .= $key;
                    $command .= "=";
                    $command .= $value;
                    $command .= "";
                }
            }
            $command .= " " . $notification->getMessage();
            return sprintf(self::NOTIFY_SEND_COMMAND.' %s', $command);
        }
    

    This will output:

    notify-send --icon=/path/to/icon  --urgency=low --category=testing "Cododeception Test Resutls"
    

    That will show the correct notification on Ubuntu systems.

    opened by esteban-serfe 2
  • Change @all to @here in hipchat example

    Change @all to @here in hipchat example

    I'm guessing this wouldn't message my whole organization, but it does consist of thousands of users, so I'd recommend switching @all to @here in the hipchat example.

    I can just see some poor soul doing this after changing the chat room name and getting in trouble or fired.

    opened by funkytaco 2
  • Bug fix when using it as Symfony Bundle

    Bug fix when using it as Symfony Bundle

    Hello, This error occurs when using the library as a Symfony Bundle

    [InvalidArgumentException] The file "services.yml" does not exist (in: vendor/namshi/notificator/src/Namshi/Notificator/Symfony/De pendencyInjection/../Resources/config).

    opened by m3doune 1
  • Adds Kahuna push notification

    Adds Kahuna push notification

    • [x] Adds kahuna client to send push notification
    • [x] Adds kahuna example and changes Readme
    • [x] Adds specs for kahuna parts
    • [x] Fixes phpspec to ver 2.5.1
    • [x] Updates symfony/process to 2.7.0
    • [x] Adds guzzle 6
    • [x] Fixes specs due to dependency changes
    • [x] Removes cordoval/phpspecs-stub (not updated in 3 years)
    • [x] Supports PHP version 5.5, 5.6 and 7.0, drops support for PHP 5.4
    opened by geshan 1
  • License? Storage?

    License? Storage?

    This looks like a really nifty library that fits into a REST service I am building but I don't see any LICENSE attached to it. Is this open source? I'm assuming so but want to ensure I follow the proper use and attribution depending on the license.

    Also, just curious. How would you handle persisting the notifications? i.e. I use this library and want to persist the notifications I send so that they can be read at a later time (think Facebook). Do you think it would be wise to use a handler for that or is that only for broadcasting the messages?

    Nice work, here, by the way. Very well thought out.

    opened by webkenny 1
  • Added a Notificator handler for SwiftMailer

    Added a Notificator handler for SwiftMailer

    • added the suggested dependencies
    • created the notification
    • created the handler
    • added specs for both of them
    • tests should be fine

    I think, on the long run, the EmailNotificationInterface should be replaced in order to make it more general, as it only accept one recipient address (BAD!) -- that was the case of our first email handler, Emailvision.

    Right now the SwiftMailer notification just accept a Swift_Message that you can customize as much as you want. Look forward to clean things a little bit for v2 (for example, NotificationInterface#getMessage() should return a 'mixed', not a string).

    opened by odino 1
  • tests are failing if you are not running them on a ubuntu box :)

    tests are failing if you are not running them on a ubuntu box :)

    • replaced shell_exec with a more robust Symfony\Component\Process\Process class
    • tests failed if you run them on a non-ubuntu box
    • tested on ubuntu 13.04 and mac osx 10.8.4

    I had to put a little logic in the test... not a good thing but at the moment I think it's the only way to ensure platform compatibility

    opened by cirpo 1
Owner
Namshi
The largest fashion e-tailer in the Middle East. #nodejs #javascript #docker #k8s #python #redis #go #kubernetes
Namshi
A PHP Library to easily send push notifications with the Pushwoosh REST Web Services.

php-pushwoosh A PHP Library to easily send push notifications with the Pushwoosh REST Web Services. First sample, creating a Pushwoosh message // Crea

gomoob 63 Sep 28, 2022
Push notifications Library for PHP

Push notifications Library for PHP Supported Protocols Protocol Supported Driver Options APNs (Token Based) ✓ APNs\Token APNs\Token\Option APNs (Certi

Norifumi SUNAOKA 3 Dec 14, 2022
Standalone PHP library for easy devices notifications push.

NotificationPusher Standalone PHP library for easy devices message notifications push. Feel free to contribute! Thanks. Contributors Cédric Dugat (Aut

Cédric Dugat 1.2k Jan 3, 2023
:computer: Send notifications to your desktop directly from your PHP script

About JoliNotif JoliNotif is a cross-platform PHP library to display desktop notifications. It works on Linux, Windows or MacOS. Requires PHP >= 7.2 (

JoliCode 1.2k Dec 29, 2022
Takes care of Apple push notifications (APNS) in your PHP projects.

Notificato Notificato takes care of push notifications in your PHP projects. Italian: notificato è: participio passato English: notified Why use Notif

Mathijs Kadijk 223 Sep 28, 2022
Notifications in PHP (notify-send, growl, etc) like that.

#Nod Notifications in PHP (notify-send, growl, etc) like that. ##Examples Letting Nod figure out the best Adapter to use (not recommend ATM, only work

Filipe Dobreira 51 Mar 26, 2019
Sends notifications via one or more channels (email, SMS, ...).

Notifier Component The Notifier component sends notifications via one or more channels (email, SMS, ...). Resources Documentation Contributing Report

Symfony 610 Jan 3, 2023
Laravel Security Notifications

This package adds security notifications to warn your users when significant security events occur so that they aren't the next victim of an attacker.

Anteris 5 Feb 8, 2022
Laravel package to launch toast notifications.

Laravel package to launch toast notifications. This package provides assistance when using toast notifications. Using the iziTOAST package, which allo

Anthony Medina 7 Nov 25, 2022
Send push notifications to apple devices (iPhone, iPad, iPod).

Apple Apn Push Send push notifications to apple devices (iPhone, iPad, iPod). Support authenticators: Certificate Json Web Token Supported protocols:

Vitaliy Zhuk 157 Dec 1, 2022
Laravel Subscribable Notifications

Laravel Subscribable Notifications This package allows you to subscribe your app Users to your app Notifications and dispatch them without specifying

Andrés Santibáñez 132 Nov 10, 2022
This package allows you to send notifications to Microsoft Teams.

Teams connector This package allows you to send notifications to Microsoft Teams. Installation You can install the package using the Composer package

skrepr 20 Oct 4, 2022
Larafirebase is a package thats offers you to send push notifications or custom messages via Firebase in Laravel.

Introduction Larafirebase is a package thats offers you to send push notifications or custom messages via Firebase in Laravel. Firebase Cloud Messagin

Kutia Software Company 264 Jan 7, 2023
Flexible Flash notifications for Laravel

Introduction Laravel Notify is a package that lets you add custom notifications to your project. A diverse range of notification design is available.

Arthur Monney 1.2k Dec 26, 2022
A package to simplify automating future notifications and reminders in Laravel

Laravel Snooze Schedule future notifications and reminders in Laravel Why use this package? Ever wanted to schedule a future notification to go out at

Thomas Kane 720 Jan 7, 2023
📨 Facebook Notifications Channel for Laravel

Facebook Notifications Channel for Laravel This package makes it easy to send notifications using the Facebook Messenger with Laravel. Contents Instal

Laravel Notification Channels 142 Dec 27, 2022
Push Notifications using Laravel

laravel-push-notification Push Notifications using Laravel PushNotification::send(['deviceToken1', 'deviceToken2',..], 'Notification Message', 'Action

Webelight Solutions 26 Jul 22, 2022
Laravel package to enable sending push notifications to devices

Laravel Push Notification Package to enable sending push notifications to devices Installation Update your composer.json file to include this package

Davi Nunes 1.2k Sep 27, 2022
Takes care of Apple push notifications (APNS) in your PHP projects.

Notificato Notificato takes care of push notifications in your PHP projects. Italian: notificato è: participio passato English: notified Why use Notif

Mathijs Kadijk 223 Sep 28, 2022