• Stars
    star
    192
  • Rank 202,019 (Top 4 %)
  • Language
    PHP
  • Created over 11 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A very lightweight library to handle notifications the smart way.

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

More Repositories

1

jose

JSON Object Signing and Encryption library for PHP.
PHP
1,786
star
2

docker-smtp

SMTP docker container
Shell
548
star
3

mockserver

Mock your backends in a matter of seconds. HTTP is King.
JavaScript
351
star
4

cuzzle

This library let's you dump a Guzzle request to a cURL command for debug and log purpose.
PHP
329
star
5

roger

A continuous integration and build server for Docker containers
JavaScript
125
star
6

winston-graylog2

Graylog2 transport for winston, a nodejs logging module
JavaScript
125
star
7

AB

AB test generator library
PHP
70
star
8

godo

Remote and local execution level 9000: go and do stuff.
Go
52
star
9

coding-challenges

Coding challenges we send out for recruitment
51
star
10

clusterjs

Clusterify your NodeJS applications and deploy without downtimes. Just like that.
JavaScript
35
star
11

NamshiVoyeurBundle

Take screenshots of your website before and after a deployment and then compare them.
PHP
32
star
12

reconfig

JavaScript configurations as they're meant to be. Kinda.
JavaScript
30
star
13

slim-slider

Light-weight, Non-jquery and RTL-supported Slider
JavaScript
29
star
14

shisha

Smoke tests made easy.
JavaScript
20
star
15

node-shell-parser

Parse commands like `ps -aux`, then relax.
JavaScript
14
star
16

keyscannerjs

A library to detect automated keyboard events from external devices (such as a barcode scanner)
JavaScript
14
star
17

docker-node-nginx-pagespeed

A simple container to...well, it's actually not that simple. Use it to run JS apps proxied by nginx. With pagespeed. Yes.
11
star
18

newrelic-winston

JavaScript
10
star
19

node-dock

Stop going crazy with running and killing docker containers. Addictive software ahead.
JavaScript
9
star
20

docker-aws-xray-daemon

AWS X-Ray daemon image
9
star
21

NMAnimatedTabBarItem

A UI library to Animate UITabBar Items
Makefile
9
star
22

node-mysql2-promise

JavaScript
9
star
23

stackdriver-pushgateway

JavaScript
8
star
24

NMMultiUnitRuler

iOS library to select different size units using a Scrollable Ruler
Swift
7
star
25

innovate

Client for the Innovate payment Gateway.
PHP
7
star
26

dollar-dom

JavaScript
6
star
27

nunjucks-setasync

Like set, but for async functions.
JavaScript
6
star
28

coding-standards

To add a newline or not, that is the question!
JavaScript
6
star
29

NMFloatLabelSearchField

A lightweight subclass of UITextField to display floating hint and suggestion list as you type
Swift
6
star
30

docker-akeneo

Docker container for Akeneo PIM
Shell
6
star
31

node-es6-seed

JavaScript
6
star
32

NamshiUtilityBundle

A collection of utilities for Sf2 apps.
PHP
6
star
33

NMLocalizedPhoneCountryView

iOS library to add support for selecting a country and its International Phone code in your app
Swift
6
star
34

PhotoViewJS

Pinch-to-zoom, double tap, pan -- dissect your images!
JavaScript
5
star
35

ng-watchers

Get a count of all the watchers AngularJS set on the current DOM
JavaScript
5
star
36

gvalue

A simple PHP library to convert Google Docs into a KeyValue array.
PHP
5
star
37

node-redis-wrapper

JavaScript
5
star
38

s3-sidecar

A container that works as a volume sidecar within a k8s pod.
Shell
5
star
39

zindex

Stream and transform your data from, to where you want
JavaScript
3
star
40

docker-elasticsearch

ElasticSearch 1.4.0 on Docker until the official dockerfile/elasticsearch image gets updated :)
3
star
41

docker-kibana4

A docker container to run kibana, compatible with found.no.
Shell
3
star
42

gulp-srizer

Add SRI hashes to your assets
JavaScript
3
star
43

smscountry

PHP library to send SMS messages through SMSCountry.
PHP
3
star
44

emailvision

This small library provides support for the "REST" interface exposed by EmailVision.
PHP
3
star
45

node-pubsub-subscriber

JavaScript
3
star
46

countjs

A small utility to count things
JavaScript
3
star
47

utils

Utilities we had to develop (arrays, strings)
PHP
2
star
48

expressjs-utils

JavaScript
2
star
49

preconfig

PHP's port of reconfig (https://github.com/namshi/reconfig)
PHP
2
star
50

qzprinty

A simple utility to print html using qz tray
JavaScript
2
star
51

we-talking-about-practice

We talking about practice, man?!?
2
star
52

lib-logger

JavaScript
1
star
53

gmaps-address-locator

Google maps based utility allowing locating of users addresses
JavaScript
1
star
54

node-file-ensure

Ensures that a file exists: if not, it creates it.
JavaScript
1
star
55

nmPhone

JavaScript
1
star
56

namshi.github.com

CSS
1
star
57

node-nmlogger

JavaScript
1
star
58

python-namutil

Python
1
star
59

js-array-into-object

Convert an array into an object (odd entries are keys, even entries are values)
JavaScript
1
star