arnapou / psr-event
Library - PSR-14.
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 (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
Date | Ref | 8.3 | 8.2 |
---|---|---|---|
09/09/2024 | 1.0.x, main | × | × |