The PHP event extension Event encapsulates the libevent library and provides an object-oriented programming interface. Developers can use PHP to quickly write event-driven applications based on the Event extension. Including event-driven non-blocking HTTP/HTTPS server and client, timers and signals.
The maintainer of the Event extension Ruslan Osmanov is a Russian programmer who also maintains 3 PHP event extensions:
- Event (libevent), Ev (libev), Eio (libeio), Event development activity is the highest.
- The underlying memory-resident, event-driven PHP frameworks like ReactPHP, WorkerMan, and AmPHP use the PHP encapsulation of the above event libraries.
PHP code example provided by Event: https://bitbucket.org/osmanov/pecl-event/src/master/examples/
PHP official website document provided by Event: https://php.net/event
A single-process event-driven non-blocking HTTP server, including non-blocking signals and periodic timers, concurrent execution of multiple services:
<?php
// 事件管理器
$base = new EventBase();
// 事件驱动非阻塞的HTTP服务器
$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('<html>Hello World</html>');
$req->sendReply(200, 'OK', $buf);
return;
});
// 事件驱动非阻塞的HTTP客户端
// EventHttpConnection::makeRequest
// 在终端 Ctrl+C 发送 SIGINT 信号给 PHP 进程
$signal = new Event($base, SIGINT, Event::SIGNAL, function() use (&$base) {
echo "\n捕获 SIGINT 信号,关闭事件循环,退出程序\n";
$base->stop();
});
$signal->add();
// 周期性定时器,每隔 1/2 秒触发一次
$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);
// 启动事件循环
$base->loop();