PHP code example of dvamigos / yii2-notifications

1. Go to this page and download the library: Download dvamigos/yii2-notifications library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dvamigos / yii2-notifications example snippets


[
    'components' => [
        'notifications' => [
            'class' => '\dvamigos\Yii2\Notifications\NotificationManager',
            'types' => [
                'text' => [
                     'my_notification' => 'This is my notification'
                ]
            ]
        ]
    ]
]


Yii::$app->notifications->push('my_notification');

[
    'components' => [
        'notifications' => [
            'class' => '\dvamigos\Yii2\Notifications\NotificationManager',
            'types' => [
                'new_user' => [
                    'text' => [
                        'title' => 'New user created!',
                        'message' => 'New user {username} is created.'
                    ],
                    'default' => [
                        'username' => ''
                    ]
                ]
            ]
        ]
    ]
]


Yii::$app->notifications->push('new_user', [
    'username' => 'JohnDoe94'
]);

public function events()
{
    self::EVENT_AFTER_INSERT => [
        new \dvamigos\Yii2\Notifications\events\PushNotification([
            'type' => 'my_notification',
            'data' => ['my_data' => 1]
        ])
    ]
}

public function events()
{
    self::EVENT_AFTER_INSERT => [
        new \dvamigos\Yii2\Notifications\events\PushNotification([
            'type' => function(PushNotification $n) {
                return 'my_type';
            },
            'data' => function(PushNotification $n) {
                return ['my_key' => $this->getPrimaryKey()];
            }
        ])
    ]
}

public function behaviors() 
{
    return [
        'notification' => [
            'class' => \dvamigos\Yii2\Notifications\events\NotificationBehavior::class,
            'events' => [
                self::EVENT_AFTER_INSERT => [
                    [
                       'class' => \dvamigos\Yii2\Notifications\events\PushNotification,
                       'type' => function(PushNotification $n) {
                            return 'my_type';
                        },
                        'data' => function(PushNotification $n) {
                            return ['my_key' => $this->getPrimaryKey()];
                        }
                    ]
                ]
            ]
        ]
    ];
}

class MyNotification extends \dvamigos\Yii2\Notifications\events\PushNotification {
    public $type = 'my_notification_type';
    
    public function init() {
        $this->data = [$this, 'handleMyData'];
        parent::init();
    }
    
    public function handleMyData(MyNotification $instance, \yii\base\Event $event)
    {
        // You logic for returning data here...
    }
}

public function behaviors() 
{
    return [
        'notification' => [
            'class' => \dvamigos\Yii2\Notifications\events\NotificationBehavior::class,
            'events' => [
                self::EVENT_AFTER_INSERT => [
                    MyNotification::class
                ]
            ]
        ]
    ];
}

[
    'components' => [
        'notifications' => [
            'class' => '\dvamigos\Yii2\Notifications\NotificationManager',
            'activeTarget' => ['database', 'android', 'ios'],
            'targets' => [
                'database' => [
                    'class' => '\dvamigos\Yii2\Notifications\targets\DatabaseTarget',
                    // ... config
                ],
                'android' => [
                    'class' => '\dvamigos\Yii2\Notifications\targets\AndroidFcmTarget',
                    'apiKey' => 'YOUR API KEY',
                    'tokenRetriever' => function(NotificationInterface $n) {
                        return $n->getData()['fcmToken'];
                    }
                ],
                'ios' => [
                    'class' => '\dvamigos\Yii2\Notifications\targets\IosApnTarget',
                    'pemFile' => '@app/path/to/your/pem/file.pem',
                    'password' => 'yourpassphrase',
                    'tokenRetriever' => function(NotificationInterface $n) {
                        return $n->getData()['iosToken'];
                    }
                ]
            ],
            'types' => [
                'new_user' => [
                    'text' => [
                        'title' => 'New user created!',
                        'message' => 'New user {username} is created.'
                    ],
                    'default' => [
                        'username' => '',
                        'fullName' => 'Unknown',
                        'gender' => 'male'
                    ]
                ]
            ]
        ]
    ]
]

Yii::$app->notifications->push('new_user', [
    'username' => 'JohnDoe94',
    'fcmToken' => "Your user's android notification token",
    'iosToken' => "Your user's ios notification token"
]);

Yii::$app->notification->pushTarget('database'); // Will only send to database.
    Yii::$app->notification->pushTarget('android'); // Will only send to android.
        Yii::$app->notification->pushTarget(['android', 'ios']); // Will only send to android and ios targets.
            // Send notification to android/ios
        Yii::$app->notification->popTarget(); // restores previous target - 'android'
        // Send notification to android
    Yii::$app->notification->popTarget(); // restores previous target - 'database'
    // Send notification to database
Yii::$app->notification->popTarget(); // restores previous target - as defined in initial configuration.

Yii::$app->notification->pushTarget(['android', 'ios']); // Will only send to android and ios targets.
// send notification
Yii::$app->notification->popTarget(); // restores previous active target.

Yii::$app->notification->getTarget('database'); // Returns DatabaseTarget

Yii::$app->notification->forTargets(['ios', 'android'], function(NotificationManager $manager) {
       $manager->push('notification'); // Will only push notification to ios, android
]);

[
    'components' => [
        'notifications' => [
            'class' => '\dvamigos\Yii2\Notifications\NotificationManager',
            'activeTarget' => ['database', 'android', 'ios'],
            'targets' => [
                'android' => [
                    'class' => '\dvamigos\Yii2\Notifications\targets\AndroidFcmTarget',
                    'apiKey' => 'YOUR API KEY',
                    'tokenRetriever' => function(NotificationInterface $n) {
                        return $n->getData()['fcmToken'];
                    }
                ]
            ],
        ]
]

class MyTokenRetrieval extends BaseObject implements dvamigos\Yii2\Notifications\TokenRetrievalInterface {
    public $target;
    
    protected $cachedTokens = [];
    
     // This example assumes you have UserTokens ActiveRecord
     // which has columns: user_id, type, token
     // And that will be used to retrieve user's token.
    public function getToken(NotificationInterface $n) {
    
         // This will cache tokens so that you dont need to
         // hit database for every notification.
         
         if (!empty($this->cachedTokens[$n->getUserId()])) {
              return $this->cachedTokens[$n->getUserId()];
         }
        
         // Returns and caches token.
         return $this->cachedTokens[$n->getUserId()] = UserTokens::find()
            ->where([
                'user_id' => $n->getId(),
                'type' => $this->target
            ])
            ->select('token')
            ->scalar() ?: '';
    }

}

[
    'components' => [
        'notifications' => [
            'class' => '\dvamigos\Yii2\Notifications\NotificationManager',
            'activeTarget' => ['database', 'android', 'ios'],
            'targets' => [
                'android' => [
                    'class' => '\dvamigos\Yii2\Notifications\targets\AndroidFcmTarget',
                    'apiKey' => 'YOUR API KEY',
                    'tokenRetriever' => [
                        'class' => MyTokenRetrieval::class,
                        'target' => 'android' 
                    ]
                ],
                'ios' => [
                    'class' => '\dvamigos\Yii2\Notifications\targets\IosApnTarget',
                    'pemFile' => '@app/path/to/your/pem/file.pem',
                    'password' => 'yourpassphrase',
                    'tokenRetriever' => [
                        'class' => MyTokenRetrieval::class,
                        'target' => 'ios' 
                    ]
                ]
            ],
        ]
]

[
    'components' => [
        'notifications' => [
            'class' => '\dvamigos\Yii2\Notifications\NotificationManager',
            'types' => [
                'new_user' => [
                    'text' => [
                        'title' => 'New user created!',
                        'message' => 'New user {username} is created.'
                    ],
                    'default' => [
                        'username' => '',
                        'fullName' => 'Unknown',
                        'gender' => 'male'
                    ]
                ]
            ]
        ]
    ]
]


<?= \dvamigos\Yii2\Notifications\widgets\NotificationList::widget([
    'containerTemplate' => '<ul>{notifications}{emptyText}</ul>',
    'emptyText' => '<li>No notifications available.</li>',
    'itemTemplate' => '
        <li>
            <span class="title">{text.title}</span>
            <span class="message">{text.message}</span>
            <span class="at">{timestamp}</span>
        </li>
    '
]); 

<?= \dvamigos\Yii2\Notifications\widgets\NotificationList::widget([
    'containerTemplate' => '<ul>{notifications}{emptyText}</ul>',
    'emptyText' => '<li>No notifications available.</li>',
    'itemTemplate' => '
        <li>
            <span class="title">{text.title}</span>
            <span class="message">{text.message}</span>
            <span class="message">User full name: {section.fullName}</span>
        </li>
    ',
    'sections' => [
        'fullName' => function($context) {
            /** @var \dvamigos\Yii2\Notifications\NotificationInterface $n */
            $n = $context['notification'];
            
            if ($n->getType() !== 'new_user') {
                return '';
            }
            
            return $n->getData()['fullName'];
        }
    ]
]);