3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

EC-CUBE4 EventListenerの使い方

Last updated at Posted at 2022-05-19

EventListenerの使い方

EC-CUBEには下記の様ないくつかのフックポイントが用意されてある。

src/Eccube/Controller/EntryController.php
    private function entryActivate(Request $request, $secret_key)
    {
        ...

        $event = new EventArgs(
            [
                'Customer' => $Customer,
            ],
            $request
        );
        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_ENTRY_ACTIVATE_COMPLETE, $event);

        ...
    }

上記は会員登録完了時のフックポイントとなり、登録完了時に行いたい処理を差し込むことが可能である。

処理を差し込む場合app/Customize配下にEventListenerディレクトリを作成し、処理を記述したファイルを作成する。

app/Customize/EventListener/SampleListener.php
<?php

namespace Customize\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class SampleListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            イベント名 => 'sampleFunction',
        ];
    }

    public function sampleFunction(EventArgs $event)
    {
        // 処理の内容
    }
}


例えば、会員登録時にポイントを付与する処理を差し込みたい場合は下記の様な形となる。

app/Customize/EventListener/AwardPointListener.php
<?php

namespace Customize\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Eccube\Entity\Customer;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AwardPointListener implements EventSubscriberInterface
{
    /**
     * @var EntityManagerInterface
     */
    protected $entityManager;

    /**
     * AwardPointListener constructor.
     *
     * @param EntityManagerInterface $entityManager
     * 
     */
    public function __construct(EntityManagerInterface $entityManager) 
    {
        $this->entityManager = $entityManager;
    }

    public static function getSubscribedEvents()
    {
        return [
            EccubeEvents::FRONT_ENTRY_ACTIVATE_COMPLETE => 'awardPointsToNewCustomer',
        ];
    }

    public function awardPointsToNewCustomer(EventArgs $event)
    {
        $Customer = $event->getArgument("Customer");

        $Customer->setPoint(500);

        $this->entityManager->persist($Customer);
        $this->entityManager->flush();
    }
}

参考文献

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?