Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Fsm Laravel Package

christhompsontldr/laravel-fsm

Robust finite state machine for Laravel with zero-config setup. Define states and transitions with guards, actions, and entry/exit callbacks. Event-driven with comprehensive transition logging, validation, caching, and support for multiple state machines per model column.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • State Management: Perfectly aligns with Laravel’s Eloquent ORM, enabling declarative state transitions for domain-driven workflows (e.g., orders, user accounts, content moderation). The package abstracts state logic into reusable definitions, reducing boilerplate and improving maintainability.
  • Event-Driven Design: Integrates seamlessly with Laravel’s event system, allowing for decoupled side effects (e.g., notifications, analytics) during transitions. The TransitionAttempted and TransitionFailed events provide hooks for observability and error handling.
  • Extensibility: Supports guards (validation), actions (side effects), and callbacks (state entry/exit), enabling fine-grained control over workflows. The fluent FsmBuilder API promotes composability and customization.
  • Multiple FSMs: Allows independent state machines per model column (e.g., approval_status and publication_status for a Document), addressing complex workflows without coupling.

Integration Feasibility

  • Laravel 12.x Compatibility: Explicitly supports Laravel 12, with PHP 8.2+ requirements. Minimal friction for adoption in modern Laravel stacks.
  • Database Agnostic: Works with any Laravel-supported database (MySQL, PostgreSQL, SQLite, etc.) via Eloquent, with no schema changes required beyond the state column.
  • Zero-Config Defaults: Out-of-the-box setup reduces onboarding time, though customization (e.g., column names, logging) is configurable via config/fsm.php.
  • Caching: Built-in caching for FSM definitions improves performance in high-traffic applications.

Technical Risk

  • Learning Curve: Developers unfamiliar with FSMs may require training to design workflows effectively. The fluent API mitigates this but introduces complexity for edge cases (e.g., nested guards).
  • State Validation Overhead: Guards and actions add runtime validation, which could impact performance if overused. Benchmarking is recommended for latency-sensitive workflows.
  • Event Storm: Excessive event listeners (e.g., for TransitionAttempted) may lead to spaghetti logic. Encourage modular event handlers (e.g., via Laravel’s HandleEvents trait).
  • Migration Path: Existing stateful models may require schema updates (e.g., adding a status column) or refactoring to adopt the trait. The package provides tools like fsm:diagram to visualize workflows pre-migration.
  • Terminal States: Misconfigured terminal states (e.g., Delivered) could block legitimate transitions. The package enforces this at the definition level but requires careful design.

Key Questions

  1. Workflow Complexity: How many distinct FSMs will the application require? The package scales well for 5–10+ workflows but may need architectural review for hundreds.
  2. Audit Requirements: Does the application need immutable audit logs? The event_logging config enables queued logging, but custom storage (e.g., PostgreSQL JSONB) may be needed for compliance.
  3. Concurrency: Will state transitions occur in high-concurrency scenarios (e.g., payment processing)? Database transactions (use_transactions: true) mitigate race conditions but add overhead.
  4. Testing Strategy: How will FSM logic be tested? The package supports dry runs (dryRun()) and diagram generation, but complex workflows may require custom test doubles.
  5. Legacy Integration: Are there existing stateful models without a status column? The default_column_name config allows flexibility, but migrations may be needed.

Integration Approach

Stack Fit

  • Laravel Ecosystem: Native integration with Eloquent, Events, Queues, and Artisan commands. No external dependencies beyond Laravel core.
  • PHP 8.2+ Features: Leverages enums (FsmStateEnum), attributes, and typed properties for type safety. Compatible with modern Laravel practices (e.g., Pint, PHPStan).
  • Testing: Supports Pest/PHPUnit via composer test. Mocking FSM transitions can be done via the HasFsm trait’s public methods (e.g., transitionFsm()).
  • DevOps: Artisan commands (fsm:diagram, fsm:cache:clear) integrate with CI/CD pipelines for workflow visualization and cache management.

Migration Path

  1. Assessment Phase:
    • Identify stateful models and their current state management (e.g., hardcoded checks, separate tables).
    • Map workflows to FSM definitions (e.g., OrderStatusFsm for orders).
  2. Pilot Migration:
    • Start with a low-risk model (e.g., Document with approval_status).
    • Add the HasFsm trait and define transitions incrementally.
    • Use dryRun() to validate transitions before enabling them.
  3. Schema Updates:
    • Add a status column (or custom column) to models if missing. Example:
      Schema::table('orders', function (Blueprint $table) {
          $table->string('status')->default(OrderStatus::Pending->value);
      });
      
  4. Configuration:
    • Publish and customize config/fsm.php (e.g., disable transactions for read-heavy workflows).
    • Configure event logging if audit trails are required.
  5. Testing:
    • Write unit tests for guards/actions using the FsmBuilder API.
    • Test edge cases (e.g., invalid transitions, concurrent requests).
  6. Rollout:
    • Deploy to staging with feature flags to toggle FSM usage.
    • Monitor TransitionFailed events for issues.

Compatibility

  • Laravel Versions: Explicitly supports Laravel 12.x. For Laravel 11 or older, check for breaking changes (e.g., event system APIs).
  • PHP Extensions: Requires pdo, mbstring, and json (standard in Laravel). No additional extensions needed.
  • Database Drivers: Works with all Eloquent-supported databases. For SQLite, ensure transactions are tested (SQLite has limited transaction isolation).
  • Queue Systems: Queued actions (e.g., queuedAction(\App\Jobs\NotifyOpsJob::class)) require Laravel Queues to be configured.

Sequencing

  1. Define Workflows: Create FSM definitions in app/Fsm/Definitions before integrating with models.
  2. Model Integration: Add HasFsm trait to models after definitions are registered.
  3. Event Listeners: Register listeners for StateTransitioned/TransitionFailed post-integration.
  4. Testing: Validate transitions in a staging environment before production rollout.
  5. Monitoring: Set up alerts for TransitionFailed events during the first 24 hours post-launch.

Operational Impact

Maintenance

  • Definition Updates: FSM definitions are version-controlled like code. Changes require cache clearing (php artisan fsm:cache:clear) and may need database migrations if states/columns change.
  • Backward Compatibility: Breaking changes (e.g., renaming a state) require coordinated deployments. Use feature flags to phase out old states.
  • Deprecation: The package follows semantic versioning. Laravel 13+ compatibility should be monitored for API changes.
  • Documentation: The package’s README and generated diagrams (fsm:diagram) serve as living documentation. Encourage team adoption of this practice.

Support

  • Debugging: The TransitionFailed event provides context for failed transitions (e.g., guard failures). Log these to a monitoring tool (e.g., Sentry, Datadog).
  • Common Issues:
    • Stuck States: Terminal states may block workflows. Design reviews should validate state machines.
    • Race Conditions: Use transactions (use_transactions: true) for critical workflows (e.g., payments).
    • Performance: Guard/actions executed on every transition. Optimize with caching or lazy evaluation.
  • Community: Low stars (8) suggest limited community support. Prioritize internal documentation and testing.

Scaling

  • Performance:
    • Caching: FSM definitions are cached by default. Clear cache during deployments.
    • Database Load: State transitions are atomic but may cause contention in high-write scenarios. Consider read replicas for reporting queries on state columns.
    • Queued Actions: Offload long-running tasks (e.g., sending emails) to queues to avoid blocking transitions.
  • Horizontal Scaling: Stateless FSM logic scales horizontally with Laravel’s queue workers and database replication.
  • Cold Starts: Laravel’s service container caches FSM definitions, reducing cold-start overhead.

Failure Modes

Failure Scenario Impact Mitigation
Database transaction rollback State and related data (e.g., payment) revert. Use use_transactions: true and validate business logic in guards.
Guard validation failure Transition blocked; user sees error. Provide user-friendly error messages via custom guard logic.
Queue worker failure (queued actions) Side effects (e.g., notifications) fail. Implement retries (Laravel Queues) and dead-letter queues for monitoring.
Cache corruption Stale FSM definitions loaded. Cache invalidation on deployments; use `fsm
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope