scriptmancer / ulak
A modern, attribute-based PHP event system with Result pattern for clean, type-safe event handling
v1.0.0
2025-02-18 10:08 UTC
Requires
- php: ^8.1
Requires (Dev)
- pestphp/pest: ^2.0
- pestphp/pest-plugin-arch: ^2.7
- symfony/var-dumper: ^7.0
README
A modern, attribute-based PHP event system with Result pattern for clean, type-safe event handling.
Features
- 🎯 Attribute-based event registration with PHP 8.1+ attributes
- 🔄 Clean Success/Failure result pattern with explicit error handling
- 🌟 Async event support with Redis integration
- 🎭 Framework agnostic design
- 🌳 PSR-compatible interfaces
- 🔍 Type-safe event handling with union types
- ⚡ High performance with attribute caching
- 🛡️ Modern PHP 8.1+ features
Requirements
- PHP 8.1 or higher
- Composer
- Redis (for async examples)
Installation
composer require scriptmancer/ulak
Quick Start
1. Basic Event Handling
use Ulak\Attributes\Event; use Ulak\Results\{Success, Failure}; class UserService { #[Event('user.registered')] #[Event('user.failed', on: 'failure')] public function register(array $data): Success|Failure { if (!$this->validate($data)) { return new Failure(new ValidationException('Invalid data')); } // Registration logic return new Success([ 'id' => $userId, 'email' => $data['email'] ]); } }
2. Async Event Processing
use Ulak\Results\AsyncSuccess; class FileService { #[Event('file.queued', on: 'async')] public function processLargeFile(File $file): AsyncSuccess|Failure { $jobId = uniqid('job-'); return new AsyncSuccess($file, $jobId) ->setProgress(0); } }
3. Event Listeners
use Ulak\EventDispatcher; $dispatcher = new EventDispatcher(); // Add a simple listener $dispatcher->addListener('user.registered', function(string $event, array $data) { // Handle user registration }); // Add a high-priority listener $dispatcher->addListener('user.registered', function(string $event, array $data) { // Handle with high priority }, EventDispatcher::PRIORITY_HIGH );
Examples
The repository includes several examples demonstrating different features:
- Basic console event handling
- Async event processing with Redis
- Web-based event handling
- Progress tracking
- Event logging
To run the examples:
# Console examples cd examples/console/basic php run.php # Web examples cd examples/web php -S localhost:8080
Development Setup
- Clone the repository:
git clone https://github.com/scriptmancer/ulak.git
cd ulak
- Install dependencies:
composer install
- Run tests:
composer test
Testing
The project uses Pest PHP for testing:
# Run all tests composer test # Run with coverage composer test:coverage
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
MIT License. See LICENSE for more information.