Event Handling PHP
Event Handlers PHP

What is Event Handling and What Does It Give

To The Code!

Let's create Event Order was placed.
1
class OrderWasPlaced
2
{
3
private string $orderId;
4
private string $productName;
5
6
public function __construct(string $orderId, string $productName)
7
{
8
$this->orderId = $orderId;
9
$this->productName = $productName;
10
}
11
12
public function getOrderId(): string
13
{
14
return $this->orderId;
15
}
16
17
public function getProductName(): string
18
{
19
return $this->productName;
20
}
21
}
Copied!
And Event Handler that will be listening to the OrderWasPlaced.
1
class NotificationService
2
{
3
#[EventHandler]
4
public function notifyAboutNewOrder(OrderWasPlaced $event) : void
5
{
6
echo $event->getProductName() . "\n";
7
}
8
}
Copied!

Running The Example

1
$eventBus->publish(new OrderWasPlaced(1, "Milk"));
Copied!

Implementation Using Lite