Performance: Defining events
This affects server-side event handling speed and how quickly the application responds to user actions or system changes.
Jump into concepts and practice - no test required
<?php namespace App\Events; use Illuminate\Support\Facades\Mail; class UserRegistered { public $user; public function __construct($user) { $this->user = $user; // pass full user object } } class SendWelcomeEmail { public function handle(UserRegistered $event) { Mail::to($event->user->email)->send(new WelcomeEmail($event->user)); } }
<?php namespace App\Events; use App\Models\User; use Illuminate\Support\Facades\Mail; class UserRegistered { public $user; public function __construct($user) { $this->user = $user; } } // Event listener directly queries database redundantly class SendWelcomeEmail { public function handle(UserRegistered $event) { $user = User::find($event->user->id); // redundant query Mail::to($user->email)->send(new WelcomeEmail($user)); } }
| Pattern | Database Queries | Server CPU Load | Response Delay | Verdict |
|---|---|---|---|---|
| Redundant queries in event listeners | Multiple per event | High | Increased by 100-200ms | [X] Bad |
| Passing full data in event object | Single per event | Low | Minimal delay | [OK] Good |
UserRegistered?php artisan make:event EventName.class OrderShipped {
public $order;
public function __construct($order) {
$this->order = $order;
}
}$order object?event() helper with a new instance of the event class.event(new OrderShipped($order)). event(OrderShipped($order)); misses new, C and D use invalid syntax.class ProductCreated {
public $product;
public function ProductCreated($product) {
$this->product = $product;
}
}__construct, not the class name.InvoicePaid that carries an Invoice object and a payment amount. Which is the best way to define its constructor?__construct and accept typed parameters for clarity and safety.