Maslosoft Mangan Logo Maslosoft Mangan Documentation
MongoDB Object Persister


Attaching Events

Events might dramatically change execution of various actions, like finding, inserting - including skipping of this actions too!

Attaching Events Basics

To attach event to model, call on() method with first parameter being one of:

  • Document instance
  • Document class name
  • Interface class name
  • Trait class name

All document classes extending from class, implementing interface or using trait that have attached event will trigger that event too

The second parameter should be name of event. Mangan built in events can be found on interfaces regarding particular functionality, for example:

Custom event types can be defined too. The best way is to create class constant with event name.

Always set isValid property of event if you wan't to continue program after event. Setting isValid to false or not setting it might stop action after event - it depends on action logic.

Set handled property to true, to stop further events processing.

Make sure that the event handlers are not bound multiple times as this might hurt performance or have unexpected results.

Always try to create immutable event handlers. In other words these handlers should not rely on application state.

Attaching to Model

The most simple way to attach event handler, it to define it right in model class constructor. Just make sure that it is attached once.


class MyDocument extends Document
    public function __construct($scenario = ScenariosInterface::Insert, $lang = '')
        // Initialize events
        static $once = false;
        if (!$once)
            Event::on(__CLASS__, EntityManagerInterface::EventAfterSave, [$this, 'notify']);
            Event::on(__CLASS__, EntityManagerInterface::EventAfterUpdate, [$this, 'notify']);
            $once = true;

    public function notify(ModelEvent $event)

In above example after saving or updating MyDocument or any derived class, the notify method will be called.

Please note that EntityManagerInterface have different events for save, insert and update operations and these need to be attached separately.

Attaching Globally

Mangan offers facility to attach events globally as an configuration option, so that these events work somewhat like database triggers. They are always active and will handle any triggered event on application lifecycle.

To create globally attached event handler, implement interface EventHandlersInterfaceand attach it to $eventHandlers property. This property should contain array of event handlers.

Each array element can be specified as following:

Example Configurations

'eventHandlers' = [
        'option' => 'My Option'