EC-CUBE4の新着情報をブラウザでPUSH通知するプラグインを作る方法です。
まずは以下のコマンドでプラグインの雛形を作ります。
プラグインコードはなんでも良いのですが、今回は「Push4」にしてください。
bin/console eccube:plugin:generate
プッシュ通知するためのTwigファイルを用意
プッシュ通知するために今回はPush.jsを使用します。
以下のTwigファイルをPlugin/Push4/Resource/template/default/snippet/push.twigに設置してください。
{% block javascripts %}
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/push.js/1.0.7/push.min.js"></script>
<script type="text/javascript">
// アクセスから30秒後に通知を受け取る許諾ポップアップを表示
setTimeout(function () {
Push.Permission.request(onGranted, onDenied);
}, 30 * 1000);
function onGranted() {
console.log('Granted!');
}
function onDenied() {
console.log('Denied');
}
if (Push.Permission.has()) {
Push.create("{{ BaseInfo.shop_name }}", {
body: "{{ News.title }}",
icon: "{{ asset('assets/img/common/favicon.ico') }}",
timeout: 4000,
onClick: function () {
{% if News.url %}
location.href = '{{ News.url }}'
{% endif %}
this.close();
}
});
}
</script>
{% endblock %}
フロントの場合のみTwigファイルを読み込む
上記で用意したTwigファイルをフロントの場合のみ読み込むイベントを用意します。
以下の内容をEvent.phpに追記してください。
<?php
namespace Plugin\Push4;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Eccube\Request\Context;
use Eccube\Event\TemplateEvent;
use Eccube\Repository\NewsRepository;
class Event implements EventSubscriberInterface {
/**
* @var \Eccube\Request\Context
*/
protected $requestContext;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @var \Eccube\Repository\NewsRepository
*/
protected $newsRepository;
public function __construct(
Context $requestContext,
EventDispatcherInterface $eventDispatcher,
NewsRepository $newsRepository
)
{
$this->requestContext = $requestContext;
$this->eventDispatcher = $eventDispatcher;
$this->newsRepository = $newsRepository;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER_ARGUMENTS => [['onKernelController', 100000000]],
];
}
public function onKernelController(FilterControllerEvent $event)
{
// フロントページでない場合はスルー
if (!$this->requestContext->isFront()) {
return;
}
if ($event->getRequest()->attributes->has('_template')) {
$template = $event->getRequest()->attributes->get('_template');
$this->eventDispatcher->addListener($template->getTemplate(), function (TemplateEvent $templateEvent) {
$templateEvent->addSnippet('@Push4/default/snippet/push.twig');
$News = $this->newsRepository->getList();
$templateEvent->setParameter('News', $News->first());
});
}
}
}
以上で完成です。
プラグインのインストールと有効化
プラグインのインストールと有効化を行うと動作します。
ちなみに上記の実装ではページをリロードするたびにプッシュ通知されます。
このプラグインのファイル一式はこちら。
