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/ */
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...
}
}
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->forTargets(['ios', 'android'], function(NotificationManager $manager) {
$manager->push('notification'); // Will only push notification to ios, android
]);
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() ?: '';
}
}