In modern PHP frameworks, event handling and message passing are essential for communication between components. They allow the system to automatically trigger specific logic when events occur, and leverage asynchronous processing to improve performance and scalability.
Event handling is usually implemented through listeners. When an event occurs, the system executes predefined callback methods. This approach decouples modules and makes dependencies clearer.
Example:
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserCreatedSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
'user.created' => 'onUserCreated',
];
}
public function onUserCreated(UserCreatedEvent $event): void
{
// Send a welcome email to the newly registered user
}
}
$dispatcher = new EventDispatcher();
$dispatcher->addListener('user.created', new UserCreatedSubscriber());
$user = new User();
$dispatcher->dispatch(new UserCreatedEvent($user));
Message passing provides another way of decoupling components, often implemented through message queues. Applications can send messages to a queue, where consumers process them asynchronously, preventing the main workflow from being blocked. Common brokers include RabbitMQ and Kafka.
Example:
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('host', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('my_queue', false, false, false, false);
$messageBody = ['email' => 'foo@example.com'];
$message = new AMQPMessage(json_encode($messageBody));
$channel->basic_publish($message, '', 'my_queue');
$channel->close();
$connection->close();
By leveraging event handling and message passing mechanisms, developers can build PHP applications that are more flexible, maintainable, and performant. Both synchronous event listeners and asynchronous message queues play key roles in large-scale systems.