@@ -644,6 +644,52 @@ You can also add hooks directly in your factory class:
644644
645645Read `Initialization `_ to learn more about the ``initialize() `` method.
646646
647+ Events
648+ ~~~~~~
649+
650+ In addition to hooks, Foundry also leverages `symfony/event-dispatcher ` and dispatches events that you can listen to,
651+ allowing to create hooks globally, as Symfony services:
652+
653+ ::
654+
655+ use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
656+ use Zenstruck\Foundry\Object\Event\AfterInstantiate;
657+ use Zenstruck\Foundry\Object\Event\BeforeInstantiate;
658+ use Zenstruck\Foundry\Persistence\Event\AfterPersist;
659+
660+ final class FoundryEventListener
661+ {
662+ #[AsEventListener]
663+ public function beforeInstantiate(BeforeInstantiate $event): void
664+ {
665+ // do something before the object is instantiated:
666+ // $event->parameters is what will be used to instantiate the object, manipulate as required
667+ // $event->objectClass is the class of the object being instantiated
668+ // $event->factory is the factory instance which creates the object
669+ }
670+
671+ #[AsEventListener]
672+ public function afterInstantiate(AfterInstantiate $event): void
673+ {
674+ // $event->object is the instantiated object
675+ // $event->parameters contains the attributes used to instantiate the object and any extras
676+ // $event->factory is the factory instance which creates the object
677+ }
678+
679+ #[AsEventListener]
680+ public function afterPersist(AfterPersist $event): void
681+ {
682+ // this event is only called if the object was persisted
683+ // $event->object is the persisted Post object
684+ // $event->parameters contains the attributes used to instantiate the object and any extras
685+ // $event->factory is the factory instance which creates the object
686+ }
687+ }
688+
689+ .. versionadded :: 2.4
690+
691+ Those events are triggered since Foundry 2.4.
692+
647693Initialization
648694~~~~~~~~~~~~~~
649695
0 commit comments