EC-CUBE4で、プラグインを使わずに処理をフックさせる方法

EC-CUBE4でフックポイントを利用する方法

EC-CUBE4では、プラグインを使うことなく フックポイントに処理をかませることができます。

これはEC-CUBE4のベースシステムであるSymfonyの機能を使ったもので、 EventSubscriberInterfaceを任意のclassに実装して利用します。

方法は簡単で、Customize\EventListener 以下に ファイルを突っ込むだけです。

<?php

namespace Customize\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class AdminFirewallListener implements EventSubscriberInterface
{
    /**
     * イベントを登録する処理
     * @return string[]
     */
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest',],
        ];
    }

    /**
     * フックポイントから呼び出される処理を記述する
     *
     * @param RequestEvent $event
     */
    public function onKernelRequest(RequestEvent $event)
    {
        // マスタリクエストでない場合は処理しない
        if (!$event->isMasterRequest()) {
            return;
        }

        // 任意の処理を書く
        // 例)アクセス元IPによる制限処理
        $request = $event->getRequest();
        $path = $request->getPathInfo();
        
        // 管理画面へのアクセスかどうか
        if (strpos($path, '/admin') === 0) {
            // 接続元IPを取得
            $ip = $request->getClientIp();
            
            // Adminへのアクセスを許可するIP設定
            // 例) 社内のグローバルIPのみ許可
            // 実装時は環境変数などで設定する方がベター
            $allow_ips = ['123.123.123.123', '111.222.333.444'];
            
            if (!in_array($ip, $allow_ips)) {
                // 403を返す
                throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
            }
        }
    }
}