docs(articles): English translation of From Magento to Symfony
en/articles/magento-to-symfony/core/events.md
new file +74
โ0
1
+
# Events
2
+
3
+
**Magento** ยท events.xml + Observer
4
+
5
+
```xml
6
+
<event name="sales_order_place_after">
7
+
<observer name="vendor_send_confirmation"
8
+
instance="Vendor\Sales\Observer\SendConfirmation"/>
9
+
</event>
10
+
```
11
+
```php
12
+
class SendConfirmation implements ObserverInterface
13
+
{
14
+
public function execute(Observer $observer): void
15
+
{
16
+
$order = $observer->getEvent()->getData('order');
17
+
// ...
18
+
}
19
+
}
20
+
21
+
$this->eventManager->dispatch(
22
+
'sales_order_place_after',
23
+
['order' => $order]
24
+
);
25
+
```
26
+
27
+
**Symfony** ยท event class + listener
28
+
29
+
```php
30
+
final class OrderPlaced
31
+
{
32
+
public function __construct(
33
+
public readonly int $orderId,
34
+
) {}
35
+
}
36
+
37
+
#[AsEventListener(event: OrderPlaced::class)]
38
+
final class SendOrderConfirmation
39
+
{
40
+
public function __invoke(OrderPlaced $event): void
41
+
{
42
+
// ...
43
+
}
44
+
}
45
+
46
+
$this->dispatcher->dispatch(new OrderPlaced($order->getId()));
47
+
```
48
+
49
+
- An event is a typed class, and the event name is its FQCN. No string keys in an array.
50
+
- There is a priority: `#[AsEventListener(priority: 10)]`, higher runs earlier. In Magento the order of observers is not guaranteed.
51
+
- `$event->stopPropagation()` stops the remaining listeners (the event has to extend `Symfony\Contracts\EventDispatcher\Event`).
52
+
- Doctrine events (`prePersist`, `postUpdate`, `onFlush`) go through a separate dispatcher: `#[AsDoctrineListener]`, `#[AsEntityListener]`.
53
+
- If the reaction is slow (an email, an ERP call), the listener puts a message into Messenger instead of doing the work itself.
54
+
55
+
**Symfony** ยท kernel listener, the equivalent of controller_action_predispatch
56
+
57
+
```php
58
+
#[AsEventListener(event: KernelEvents::REQUEST, priority: 20)]
59
+
final class MaintenanceListener
60
+
{
61
+
public function __construct(
62
+
#[Autowire(env: 'bool:MAINTENANCE')]
63
+
private bool $maintenance,
64
+
) {}
65
+
66
+
public function __invoke(RequestEvent $event): void
67
+
{
68
+
if (!$this->maintenance || !$event->isMainRequest()) {
69
+
return;
70
+
}
71
+
$event->setResponse(new Response('Maintenance', 503));
72
+
}
73
+
}
74
+
```