Skip to content

Instantly share code, notes, and snippets.

@NickHatBoecker
Last active July 30, 2019 08:03
Show Gist options
  • Save NickHatBoecker/8c234ffad52e3c85c271f85ad1d24af6 to your computer and use it in GitHub Desktop.
Save NickHatBoecker/8c234ffad52e3c85c271f85ad1d24af6 to your computer and use it in GitHub Desktop.
Push Notifications für Webapps mit OneSignal
"require": {
"php-http/guzzle6-adapter": "^1.1",
"norkunas/onesignal-php-api": "dev-master"
}
<?php
namespace AppBundle\Service;
use GuzzleHttp\Client;
use Http\Client\Common\HttpMethodsClient;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;
use Http\Message\MessageFactory\GuzzleMessageFactory;
use OneSignal\Config;
use OneSignal\OneSignal;
class NotificationHelper
{
private $api;
public function __construct($appId, $appAuthKey)
{
// Prepare client
$guzzle = new Client();
$client = new HttpMethodsClient(
new GuzzleAdapter($guzzle),
new GuzzleMessageFactory()
);
// Prepare config
$config = new Config();
$config->setApplicationId($appId);
$config->setApplicationAuthKey($appAuthKey);
$this->api = new OneSignal($config, $client);
}
/**
* Trigger normal text message
*
* @param string $message
*/
public function triggerMessage($message)
{
$this->sendMessage($message);
}
/**
* Send actual message
*
* @param string $title
* @param string $body
* @param string $url
*/
private function sendMessage($body, $url = null)
{
$options = array(
'headings' => array(
'en' => 'Testanwendung',
),
'contents' => array(
'en' => $body,
),
'included_segments' => array('All'),
);
if ($url) {
$options['url'] = $url;
}
$this->api->notifications->add($options);
}
}
<?php
namespace AppBundle\Controller;
class PushNotificationController extends Controller
{
public function indexAction()
{
$notificationHelper = $this->get('nhb_notification_helper');
$notificationHelper->triggerMessage('Dies ist eine Push Notification');
}
}
services:
nhb_notification_helper:
class: AppBundle\Service\NotificationHelper
arguments:
appId: "%one_signal.app_id%"
appAuthKey: "%one_signal.app_auth_key%"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment