aza/libevent

AzaLibEvent - LibEvent PHP 绑定的简单、强大且易于使用的 OOP 封装。Anizoptera CMF 的组件。

v1.1 2013-05-28 13:02 UTC

This package is not auto-updated.

Last update: 2024-09-14 13:28:31 UTC


README

为 LibEvent PHP 绑定提供简单、强大且易于使用的 OOP 封装。

https://github.com/Anizoptera/AzaLibEvent

Build Status

目录

  1. 简介
  2. 要求
  3. 安装
  4. 示例
  5. 致谢
  6. 许可
  7. 链接

简介

主要特性

  • 方便、全面文档化并已在生产环境中测试的 API;
  • 计时器和间隔系统(请参阅 EventBase::timerAdd);
  • 针对分叉的特殊基础重新初始化(请参阅 EventBase::reinitialize);
  • 使用异常处理错误;
  • 自动清理资源;

要求

  • PHP 5.2.0(或更高版本);
  • libevent;

安装

安装 AzaLibEvent 的推荐方式是 通过 composer。您可以在 Packagist 上查看 软件包信息

{
	"require": {
		"aza/libevent": "~1.0"
	}
}

示例

示例 #1 - 使用基本 API 轮询 STDIN

请参阅 examples/basic_api.php

/**
 * Callback function to be called when the matching event occurs
 *
 * @param resource $fd     File descriptor
 * @param int      $events What kind of events occurred. See EV_* constants
 * @param array    $args   Event arguments - array(Event $e, mixed $arg)
 */
function print_line($fd, $events, $args)
{
	static $max_requests = 0;
	$max_requests++;

	/**
	 * @var $e    Event
	 * @var $base EventBase
	 */
	list($e, $base) = $args;

	// exit loop after 10 writes
	if ($max_requests == 10) {
		$base->loopExit();
	}

	// print the line
	echo fgets($fd);
}

// Create base
$base = new EventBase;

// Setup and enable event
$ev = new Event();
$ev->set(STDIN, EV_READ|EV_PERSIST, 'print_line', $base)
		->setBase($base)
		->add();

// Start event loop
$base->loop();

示例 #2 - 使用缓冲事件 API 轮询 STDIN

请参阅 examples/buffered_api.php

/**
 * Callback to invoke where there is data to read
 *
 * @param resource $buf  File descriptor
 * @param array    $args Event arguments - array(EventBuffer $e, mixed $arg)
 */
function print_line($buf, $args)
{
	static $max_requests;
	$max_requests++;

	/**
	 * @var $e    EventBuffer
	 * @var $base EventBase
	 */
	list($e, $base) = $args;

	// exit loop after 10 writes
	if ($max_requests == 10) {
		$base->loopExit();
	}

	// print the line
	echo $e->read(4096);
}

/**
 * Callback to invoke where there is an error on the descriptor.
 * function(resource $buf, int $what, array $args(EventBuffer $e, mixed $arg))
 *
 * @param resource $buf  File descriptor
 * @param int      $what What kind of error occurred. See EventBuffer::E_* constants
 * @param array    $args Event arguments - array(EventBuffer $e, mixed $arg)
 */
function error_func($buf, $what, $args) {}


// I use Base::getEventBase() to operate always with the
// same instance, but you can simply use "new EventBase()"

// Get event base
$base = Base::getEventBase();

// Create buffered event
$ev = new EventBuffer(STDIN, 'print_line', null, 'error_func', $base);
$ev->setBase($base)->enable(EV_READ);

// Start loop
$base->loop();

致谢

AzaLibEvent 是 Anizoptera CMF 的一部分,由 Amal Samally(amal.samally at gmail.com)和 AzaGroup 团队编写。

许可

MIT 许可下发布。

链接