Events
Last updated
Was this helpful?
Was this helpful?
<?php
public static function on($eventName, $listener, $priority = 0) {}<?php
public static function run($eventName, $payload = null) {}<?php
public static function runs(array $events) {}<?php
[
'EventName1' => $payload1,
'EventName2' => $payload2,
...
]Events::on('UserRegistered', function ($user) {
echo "Welcome, {$user['name']}!<br>";
}, 10); // Priority 10
Events::on('UserRegistered', function ($user) {
echo "Sending welcome email to {$user['email']}...<br>";
}, 5); // Priority 5
$user = ['name' => 'John Doe', 'email' => '[email protected]'];
Events::run('UserRegistered', $user);
// ------------------------------ Output ------------------------------
// Welcome, John Doe!
// Sending welcome email to [email protected]...class NotifyAdmin
{
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function handle()
{
echo "Notifying admin about new user: {$this->user['name']}<br>";
}
}Events::on('UserRegistered', NotifyAdmin::class, 8); // Priority 8
// ------------------------------ Output ------------------------------
// Welcome, John Doe!
// Notifying admin about new user: John Doe
// Sending welcome email to [email protected]...<?php
// Register event 'OrderPlaced'
Events::on('OrderPlaced', function ($order) {
echo "Order #{$order['id']} has been placed.<br>";
});
// Triggering Mmultiple Events
$events = [
'UserRegistered' => $user,
'OrderPlaced' => ['id' => 12345],
];
Events::runs($events);
// ------------------------------ Output ------------------------------
// Welcome, John Doe!
// Notifying admin about new user: John Doe
// Sending welcome email to [email protected]...
// Order #12345 has been placed.