arnapou/psr-event

v1.0.0 2024-09-09 18:42 UTC

This package is auto-updated.

Last update: 2024-09-09 16:45:41 UTC


README

pipeline coverage

KISS(保持简单,傻瓜)PSR(PHP标准建议)类。

安装

composer require arnapou/psr-event

packagist 👉️ arnapou/psr-event

何时使用此库

  • 您需要关于PSR的简单装饰器、代理、适配器等
  • 您需要覆盖基本功能的简单实现

示例PSR-14事件调度器

我们可以实现PSR的方式非常广泛。

我基本上构建了一些“对象总线”,根据PHP类型提示对事件进行路由。

在PSR中,一个事件可以是任何对象,您可以通过为该对象实现StoppableEventInterface来停止其传播。

这非常简单、高效且直观。

$dispatcher = new \Arnapou\Psr\Psr14EventDispatcher\ClassEventDispatcher();
$dispatcher->listen(function(DateTime $date) {
    echo "DateTime: " . $date->format('Y-m-d') . "\n";
});
$dispatcher->listen(function(DateTimeImmutable $date) {
    echo "DateTimeImmutable: " . $date->format('Y-m-d') . "\n";
});
$dispatcher->listen(function(DateTimeInterface $date) {
    echo "DateTimeInterface: " . $date->format('Y-m-d') . "\n";
});

$dispatcher->dispatch(new DateTime('2023-10-10'));
// This will echo
// DateTimeInterface: 2023-10-10
// DateTime: 2023-10-10

PHP处理器:为了便于记录PHP崩溃等,我创建了一个使用我的调度器的类

$phpHandlers = new \Arnapou\Psr\Psr14EventDispatcher\PhpHandlers($logger);
$phpHandlers->registerAll();

// You can decide to throw ErrorException on notices
$phpHandlers->throwErrorNotice();

// You can hook to do what you want on exceptions or errors
$phpHandlers->listen(function (\Throwable $throwable) {
    if ($throwable->getCode() === 666) {
        exit;
    }
});

// Or on shell signals
$phpHandlers->listen(function (\Arnapou\Psr\Psr14EventDispatcher\Event\SignalEvent $event) use ($logger) {
    if ($event->value === SIGINT) {
        $logger->emergency('Somebody CTRL-C the process');
    }
});

// Or on process exit, you also can carry your own infos in the object used
$phpHandlers->shutdownEvent->setValue('AppName', 'my-app');
$phpHandlers->listen(function (\Arnapou\Psr\Psr14EventDispatcher\Event\ShutdownEvent $event) use ($logger) {
    $appName = $event->getValues()['AppName'];
    $logger->debug('The process elapsed '. $event->getElapsedTime() . ' seconds for app ' . $appName);
});

PHP版本

日期引用8.38.2
09/09/20241.0.x,主要版本××