Using the PHP Event Extension for Event‑Driven Non‑Blocking HTTP Servers
The PHP Event extension wraps the libevent library to provide an object‑oriented API for building event‑driven, non‑blocking HTTP servers and clients, timers, and signal handling, with example code and links to documentation and related extensions.
The PHP Event extension wraps the libevent library and offers an object‑oriented programming interface, allowing developers to quickly create event‑driven applications such as non‑blocking HTTP/HTTPS servers and clients, timers, and signal handlers.
The extension is maintained by Russian programmer Ruslan Osmanov, who also maintains two other PHP event extensions—Ev (libev) and Eio (libeio)—with Event (libevent) being the most actively developed.
Popular PHP event‑driven frameworks like ReactPHP, WorkerMan, and AmPHP rely on these underlying event libraries.
Example code for the Event extension is available at https://bitbucket.org/osmanov/pecl-event/src/master/examples/ , and the official documentation can be found at https://php.net/event .
A single‑process, event‑driven, non‑blocking HTTP server with signal handling, a periodic timer, and concurrent services is demonstrated below:
<?php
// Event manager
$base = new EventBase();
// Event‑driven non‑blocking HTTP server
$http = new EventHttp($base);
$http->bind('0.0.0.0', 8888);
$http->setDefaultCallback(function($req) {
$buf = new EventBuffer();
$req->addHeader('Content-Type', 'text/html; charset=utf-8', EventHttpRequest::OUTPUT_HEADER);
$buf->add('
Hello World
');
$req->sendReply(200, 'OK', $buf);
return;
});
// Event‑driven non‑blocking HTTP client (EventHttpConnection::makeRequest)
// Capture SIGINT (Ctrl+C) to stop the loop
$signal = new Event($base, SIGINT, Event::SIGNAL, function() use (&$base) {
echo "\n捕获 SIGINT 信号,关闭事件循环,退出程序\n";
$base->stop();
});
$signal->add();
// Periodic timer that fires every half second
$timer = new Event($base, -1, Event::TIMEOUT | Event::PERSIST, function() use (&$timer) {
echo date('Y-m-d H:i:s') . "\n";
});
$timer->add(1/2);
// Start the event loop
$base->loop();Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.