arnapou/psr-event

Library - PSR-14.

v1.1.0 2024-11-24 20:47 UTC

This package is auto-updated.

Last update: 2024-12-24 21:33:07 UTC


README

pipeline coverage

KISS (Keep It Simple Stupid) PSR (PHP Standards Recommendations) classes.

Installation

composer require arnapou/psr-event

packagist 👉️ arnapou/psr-event

When it is worth to use this library

  • you need simple decorators, proxies, adapters, ... about PSR's
  • you need simple implementations covering the basics

Example PSR-14 Event Dispatcher

The way we can implement the PSR is very wide.

I basically built some "object bus" with routing of events based on php type hinting.

In the PSR, an event can be any object, you can stop the propagation implementing a StoppableEventInterface for that object.

This is very simple, efficient and intuitive.

$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 Handlers : in order to ease the logging of php crashs, etc ... I made a class which uses my dispatcher

$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 versions

DateRef8.48.38.2
24/11/20241.1.x, main×××
09/09/20241.0.x××