EC-CUBE4で、controllerだとリダイレクトするのは簡単。
$this->redirectToRoute('hoge');
でも、eventListnerだと???
・__constructでcontainerを取得する
・containerからrouterを取得する
・redirectResponseオブジェクトを作って、イベントのレスポンスとして返す
の手順で実現できた。
(もっと簡単な方法あるのだろうか…)
<?php
namespace Customize\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Generator\urlGeneratorInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class hogeEvent implements EventSubscriberInterface
{
protected $container;
protected $router;
/**
* hogeListener constructor.
*/
public function __construct(
ContainerInterface $container
) {
$this->container = $container;
$this->router = $this->container->get('router');
}
public static function getSubscribedEvents()
{
return [
// hoge処理完了
EccubeEvents::FRONT_HOGE_COMPLETE => 'onFrontHogeComplete',
];
}
/**
* hoge時りダイレクト先を変更する処理
*
* @param EventArgs $event
*/
public function onFrontHogeComplete(EventArgs $event)
{
$url = $this->router->generate('shopping_login'); //例えば、shoppingのログインページ
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
containerでget(‘サービスのID’)でサービスを取得、メソッドが使えるようになるので、超便利。というか万能では?
$router = $this->container->get('router');
$abstractController = $this->container->get('Eccube\Controller\AbstractController');
参考:
[EC-CUBE4始めました]
https://blog.e2info.co.jp/2018/11/21/ec-cube4%E5%A7%8B%E3%82%81%E3%81%BE%E3%81%97%E3%81%9F/