Skip to content

tarfin-labs/event-machine

Repository files navigation

EventMachine

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Event-driven state machines for Laravel

Documentation · Installation · Why EventMachine?


Why EventMachine?

Your business logic deserves better than nested if-statements.

EventMachine brings the power of finite state machines to Laravel, inspired by XState. Define your states, transitions, and behaviors declaratively - and let the machine handle the complexity.

The Problem

// Without state machines: scattered conditionals, hidden rules, impossible to test
if ($order->status === 'pending' && $user->can('approve') && !$order->isExpired()) {
    if ($order->total > 10000 && !$order->hasSecondApproval()) {
        // More nested logic...
    }
}

The Solution

// With EventMachine: clear states, explicit transitions, testable behaviors
MachineDefinition::define(
    config: [
        'initial' => 'pending',
        'states' => [
            'pending' => [
                'on' => [
                    'APPROVE' => [
                        'target' => 'approved',
                        'guards' => [CanApproveGuard::class, NotExpiredGuard::class],
                    ],
                ],
            ],
            'approved' => [
                'entry' => NotifyCustomerAction::class,
            ],
        ],
    ],
);

Key Benefits

Feature Description
Event Sourced Every transition persisted. Full audit trail. Replay history.
Behaviors Guards validate, calculators compute, actions execute.
Testable Fake any behavior. Assert states. Verify transitions.
Type-Safe Context Spatie Data powered. Validated. IDE autocompletion.
Archival Compress millions of events. Restore any machine instantly.
Laravel Native Eloquent, DI, Artisan commands. Built for Laravel.

Installation

composer require tarfin-labs/event-machine
php artisan vendor:publish --tag="event-machine-migrations"
php artisan migrate

Eloquent Integration

class Order extends Model
{
    use HasMachines;

    protected $casts = [
        'machine' => MachineCast::class.':'.OrderMachine::class,
    ];
}

// Use it naturally
$order = Order::create();
$order->machine->send(['type' => 'SUBMIT']);
$order->machine->send(['type' => 'APPROVE']);

$order->machine->state->matches('approved'); // true
$order->machine->state->history->count();    // 3 events tracked

Documentation

For guards, actions, calculators, hierarchical states, validation, testing, and more:

Read the Documentation →

Credits

License

MIT License. See LICENSE for details.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 7

Languages