Giter Club home page Giter Club logo

yii2-notifications's Introduction

๐Ÿ”” Notifications for Yii2

This Yii2 extension provides support for sending notifications across a variety of delivery channels, including mail, SMS, Slack, Telegram etc. Notifications may also be stored in a database so they may be displayed in your web interface.

Typically, notifications should be short, informational messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an "Invoice Paid" notification to your users via the email and SMS channels.

Latest Stable Version Scrutinizer Code Quality Build Status Code Climate

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist tuyakhov/yii2-notifications "*"

or add

"tuyakhov/yii2-notifications": "*"

to the require section of your composer.json file.

Usage

The following example shows how to create a Notifier instance and send your first notification:

$notifier = new \tuyakhov\notifications\Notifier([
  'channels' => [...],
]);
$notifier->send($recipients, $notifications);

Notifier is often used as an application component and configured in the application configuration like the following:

[
   'components' => [
       'notifier' => [
           'class' => '\tuyakhov\notifications\Notifier',
           'channels' => [
               'mail' => [
                   'class' => '\tuyakhov\notifications\channels\MailChannel',
                   'from' => '[email protected]'
               ],
               'sms' => [
                   'class' => '\tuyakhov\notifications\channels\TwilioChannel',
                   'accountSid' => '...',
                   'authToken' => '...',
                   'from' => '+1234567890'
               ],
               'telegram' => [
                    'class' => '\tuyakhov\notifications\channels\TelegramChannel',
                    'botToken' => '...'
                ],
               'database' => [
                    'class' => '\tuyakhov\notifications\channels\ActiveRecordChannel'
               ]
           ],
       ],
   ],
]

Once the component is configured it may be used for sending notifications:

$recipient = User::findOne(1);
$notification = new InvoicePaid($invoice);

Yii::$app->notifier->send($recipient, $notification);

Each notification class should implement NotificationInterface and contain a viaChannels method and a variable number of message building methods (such as exportForMail) that convert the notification to a message optimized for that particular channel. Example of a notification that covers the case when an invoice has been paid:

use tuyakhov\notifications\NotificationInterface;
use tuyakhov\notifications\NotificationTrait;

class InvoicePaid implements NotificationInterface
 {
    use NotificationTrait;
    
    private $invoice;
    
    public function __construct($invoice) 
    {
        $this->invoice = $invoice;
    }

    /**
     * Prepares notification for 'mail' channel
     */
    public function exportForMail() {
        return Yii::createObject([
           'class' => '\tuyakhov\notifications\messages\MailMessage',
           'view' => ['html' => 'invoice-paid'],
           'viewData' => [
               'invoiceNumber' => $this->invoice->id,
               'amount' => $this->invoice->amount
           ]
        ])
    }
    
    /**
     * Prepares notification for 'sms' channel
     */
    public function exportForSms()
    {
        return \Yii::createObject([
            'class' => '\tuyakhov\notifications\messages\SmsMessage',
            'text' => "Your invoice #{$this->invoice->id} has been paid"
        ]);
    }
    
    /**
     * Prepares notification for 'database' channel
     */
    public function exportForDatabase()
    {
        return \Yii::createObject([
            'class' => '\tuyakhov\notifications\messages\DatabaseMessage',
            'subject' => "Invoice has been paid",
            'body' => "Your invoice #{$this->invoice->id} has been paid",
            'data' => [
                'actionUrl' => ['href' => '/invoice/123/view', 'label' => 'View Details']
            ]
        ]);
    }
 }

You may use the NotifiableInterface and NotifiableTrait on any of your models:

use yii\db\ActiveRecord;
use tuyakhov\notifications\NotifiableTrait;
use tuyakhov\notifications\NotifiableInterface;

class User extends ActiveRecord implements NotifiableInterface 
{
   use NotifiableTrait;
   
   public function routeNotificationForMail() 
   {
        return $this->email;
   }
}

Database notifications

The database notification channel stores the notification information in a database table.
You can query the table to display the notifications in your application's user interface. But, before you can do that, you will need to create a database table to hold your notifications. To do this, you can use the migration that comes with this extension:

yii migrate --migrationPath=@vendor/tuyakhov/yii2-notifications/src/migrations

or

'controllerMap' => [
    ...
    'migrate' => [
        'class' => 'yii\console\controllers\MigrateController',
        'migrationNamespaces' => [
            'tuyakhov\notifications\migrations',
        ],
    ],
    ...
],
php yii migrate/up

Accessing The Notifications
Once notifications are stored in the database, you need a convenient way to access them from your notifiable entities. The NotifiableTrait, which comes with this extension, includes a notifications relationship that returns the notifications for the entity. To fetch notifications, you may access this method like any other ActiveRecord relationship.

$model = User::findOne(1);
foreach($model->notifications as $notification) {
    echo $notification->subject;
}

If you want to retrieve only the "unread" notifications, you may use the unreadNotifications relationship.

$model = User::findOne(1);
foreach($model->unreadNotifications as $notification) {
    echo $notification->subject;
}

You can access custom JSON data that describes the notification and was added using DatabaseMessage:

/** @var $notificatiion tuyakhov\notifications\models\Notificatios */
$actionUrl = $notification->data('actionUrl'); // ['href' => '/invoice/123/pay', 'label' => 'Pay Invoice']

Marking Notifications As Read
Typically, you will want to mark a notification as "read" when a user views it. The ReadableBehavior in Notification model provides a markAsRead method, which updates the read_at column on the notification's database record:

$model = User::findOne(1);
foreach($model->unreadNotifications as $notification) {
    $notification->markAsRead();
    
    // the following methods are also available
    $notification->markAsUnread();
    $notification->isUnread();
    $notification->isRead();
}

yii2-notifications's People

Contributors

antonacc avatar gitrequests avatar julielesss avatar mrbig00 avatar tuyakhov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-notifications's Issues

Enhancement: $link attribute for "database" channel

Add support for URL storing for notifications in database. I think it is good feature for this awesome extension. Need to update Notification Model class.

Right now the solution is parsing $body attribute for storing url, for example:

$notification->body = "/some/url||message";

...

    $urlMessage = explode('||', $notification->body, 2);
    $url = count($urlMessage) == 2 ? $urlMessage[0] : null;
    $message = count($urlMessage) == 2 ? $urlMessage[1] : $urlMessage[0];

update read me

A per the current read me, the interface methods exportForMail() and exportForSms() do not exist but what is available is the exportFor($channel) function which expects the channel parameter and the broadcastOn() functions.
This document does not reflect on the current modifications and because of that setting it up is a problem. So please update it coz I really need to use your great extension, just not certain how to. FYI examples on using the database channel would greatly help.

Calling unknown method: yii\db\ActiveQuery::addOnCondition()

Yii version: 2.0.14

Error using "database" channel:

Unknown Method โ€“ yii\base\UnknownMethodException

Calling unknown method: yii\db\ActiveQuery::addOnCondition()

tuyakhov/yii2-notifications/src/NotifiableTrait.php at line 73 and 78:

    public function getNotifications()
    {
        /** @var $this BaseActiveRecord */
        return $this->hasMany(Notification::className(), ['notifiable_id' => 'id'])
            ->addOnCondition(['notifiable_type' => get_class($this)]);
    }
 
    public function getUnreadNotifications()
    {
        return $this->getNotifications()->addOnCondition(['read_at' => null]);
    }

Solved by rename method to "onCondition()". Is it yii2 version specified or not?

Error sending many notifications in ActiveRecordChannel

Find this issue when applying batch action...

Try to send notifications like this:

Yii::$app->notifier->send($user1, $notification1);
Yii::$app->notifier->send($user1, $notification2);
Yii::$app->notifier->send($user2, $notification3);

I know that notifications may sending in array... But it is impossible in some use cases.

Right now, if many noty sending in this way, second query (and the following) in ActiveRecordChannel.php loads Existing Model! And we do insert() function on Existing model!

In my project this issue do not sending some data in Database ONLY in batch insert (there is some other fields in DB, since i use a different ActiveRecordChannel):
screenshot from 2018-11-06 18-25-58

My solution is to create new Model before load Data (Change in ActiveRecordChannel.php from line 46):

$class = $this->model;
$model = \Yii::createObject($class::className());

if ($model->load($data, '')) {
      return $model->insert();
}

This issue need to checking by contributors, since i use extending ActiveRecordChannel. But inserting on existing Model is not right way.

Wrong call to insert

ActiveRecordInterface::insert does not use second param as an input of values, it only filter which properties must be allowed.

ActiveRecordChannel should have method send like this:

 public function send(NotifiableInterface $recipient, NotificationInterface $notification)
    {
        /** @var DatabaseMessage $message */
        $message = $notification->exportFor('database');
        list($notifiableType, $notifiableId) = $recipient->routeNotificationFor('database');

        $this->model->level = $message->level;
        $this->model->subject = $message->subject;
        $this->model->body = $message->body;
        $this->model->notifiable_type = $notifiableType;
        $this->model->notifiable_id = $notifiableId;

        return $this->model->insert(true);
    }

Migration NameSpace

Hi , I have error when execute yii migrate
it's caused by namespace of the migration.
Please add this line
namespace tuyakhov\notifications\migrations;
in m180824_090744_create_notification_table.php

Thanks!!
Regards

SQL error while migrate/up

Error message when yii migrate execute:
create table notification ...Exception 'yii\db\Exception' with message 'SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created_at'

Solved by adding default value to migration:
@vendor/tuyakhov/yii2-notifications/src/migrations

...
            'created_at' => $this->timestamp()->null(),
...

PHP 7.2.10-0ubuntu0.18.04.1 (cli)
MySQL 5.7.23-0ubuntu0.18.04.1 (Ubuntu)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.