Listening to Events

There are two ways to listen to events, using direct listeners or subscribers. The difference between these two is that a subscriber allows the module providing the subscriber to wire up the handlers in the module that owns it without touching the EventDependencyProvider exception’s initial subscriber initialization. It is best to use a subscriber from the beginning as this simplifies future listener registration. When you need to listen to specific listener use \Pyz\Zed\Event\EventDependencyProvider::getEventListenerCollection.

To listen to events in the system you need to add listener plugins. Listener is a class which extends plugins and implements EventListenerInterface. This plugin must be placed in the module we want to listen to: Communication\Plugin\Product\ProductRelationAbstractProductChangeListener.

For example: Each listener plugin must implement \Spryker\Service\Event\Dependency\Plugin\EventListenerInterface.

<?php
namespace Spryker\Zed\ProductRelation\Communication\Plugin\Product;

use Spryker\Zed\Event\Dependency\Plugin\EventListenerInterface;
use Spryker\Shared\Kernel\Transfer\TransferInterface;
use Spryker\Zed\Kernel\Communication\AbstractPlugin;

/**
 * @method \Spryker\Zed\ProductRelation\Business\ProductRelationFacade getFacade()
 * @method \Spryker\Zed\ProductRelation\Communication\ProductRelationCommunicationFactory getFactory()
 */
class ProductRelationAbstractProductChangeListener extends AbstractPlugin implements EventListenerInterface
{

    /**
     * @param \Spryker\Shared\Kernel\Transfer\TransferInterface|\Generated\Shared\Transfer\ProductAbstractTransfer $eventTransfer
     *
     * @return void
     */
    public function handle(TransferInterface $eventTransfer)
    {
        $this->getFacade()->applyRulesToProductAbstract($eventTransfer);
    }

}

Add this listener to \Pyz\Zed\Event\EventDependencyProvider::getEventListenerCollection

For example:

$eventCollection->addListener(ProductEvents::PRODUCT_ABSTRACT_BEFORE_CREATE, new ProductRelationAbstractProductChangeListener())

Related Topics Link IconRelated Topics