arnapou/ psr-event
v1.0.0
2024-09-09 18:42 UTC
Requires
- php: ~8.2.0 || ~8.3.0
- arnapou/psr-log: ^1.0
- psr/event-dispatcher: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.52
- phpstan/extension-installer: ^1.3
- phpstan/phpstan: ^1.10
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpstan/phpstan-strict-rules: ^1.5
- phpunit/php-code-coverage: ^11.0
- phpunit/phpunit: ^11.0
Provides
README
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.3 | 8.2 |
---|---|---|---|
09/09/2024 | 1.0.x,主要版本 | × | × |