Add events
Edit on GitHubWhen adding an event, make sure you first decide what kind of events you want to trigger in your code. You define events in a class by declaring their literal string values, such as ModuleName.subject.action
. An event’s value uniquely identifies an event. All listeners attached to an event are executed when a module triggers an event.
For example, to perform an action before persisting a product abstract entity, do the following:
- Create a class to hold all the module events:
Spryker\Shared\Product\ProductConfig.php
- Add the following constant
ProductConfig::PRODUCT_ABSTRACT_BEFORE_CREATE
with the valueProduct.product_abstract.before.create
. The first part in this example value is the module name, then the subject, and lastly the action. You can define any unique name, just keep it literal for the sake of code clarity. - Trigger the event before the entity is persisted using the event facade
\Spryker\Zed\Event\EventFacadeInterface::trigger
method which accepts two arguments:eventName
, which is the name of the event we created beforeProductConfig::PRODUCT_ABSTRACT_BEFORE_CREATE
andTransferInterface
, which is the transfer object you want to pass to the event listener.
When multiple modules use the same events, we recommend redefining the constants in the secondary modules and binding them to the primary module’s constants with the @uses
PHP tag.
class ProductStorageConfig extends AbstractBundleConfig
{
/**
* @uses ProductConfig::PRODUCT_ABSTRACT_BEFORE_CREATE // primary constant
*
* @var string
*/
public const PRODUCT_ABSTRACT_BEFORE_CREATE = 'Product.product_abstract.before.create'; // secondary constant
}
Thank you!
For submitting the form