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: The package excels at modeling complex workflows (e.g., order processing, user verification) where state transitions require validation, side effects, and auditability. Its event-driven design aligns well with Laravel’s ecosystem (e.g., queues, events, observers).
  • Separation of Concerns: The fluent API (FsmBuilder) decouples state logic from models, adhering to clean architecture principles. Guards, actions, and callbacks are modular, enabling maintainable business rules.
  • Extensibility: Supports multiple FSMs per model (e.g., approval_status and publication_status for a Document), making it adaptable to domain-specific needs.
  • Laravel Synergy: Leverages Laravel features like transactions, queues, events, and enums, reducing boilerplate and integrating seamlessly with existing systems.

Integration Feasibility

  • Low Friction: Zero-config setup with sensible defaults (e.g., status column, transactional writes). Minimal changes required to adopt.
  • Model Integration: The HasFsm trait is lightweight and non-intrusive, requiring only:
    1. Enum definition for states.
    2. FSM definition class (auto-discovered via service provider).
    3. Trait inclusion in the model.
  • Backward Compatibility: Designed for Laravel 12.x, with PHP 8.1+ support. No breaking changes expected for minor updates.

Technical Risk

  • Learning Curve: Developers unfamiliar with FSMs or Laravel’s event system may require training. The fluent API mitigates this but introduces complexity for simple use cases.
  • Performance Overhead:
    • Logging: Enabled by default (configurable). Audit trails add I/O but are optional.
    • Caching: Definitions are cached, but dynamic FSMs (e.g., runtime-generated) may require manual cache invalidation.
  • State Validation: Guards/actions must be idempotent and handle edge cases (e.g., concurrent transitions). Poorly written guards could lead to race conditions.
  • Testing Complexity: State machines require comprehensive test coverage for all transitions, guards, and side effects. The package provides utilities (e.g., dryRun) but doesn’t enforce testing strategies.

Key Questions

  1. Domain Complexity:
    • Are workflows linear (e.g., draft → published) or branching (e.g., review → approved/rejected)? The package handles both but may need custom guards for complex logic.
  2. Audit Requirements:
    • Is immutable logging critical? The package supports event logging, but custom storage (e.g., database vs. ELK) may be needed.
  3. Concurrency:
    • How are race conditions handled (e.g., two users triggering pay simultaneously)? The package uses transactions but may need application-level locks for critical paths.
  4. Migration Path:
    • Are existing state columns enums or strings? The package supports both but enforces type safety post-adoption.
  5. Team Skills:
    • Does the team have experience with event-driven architectures? If not, additional training or scaffolding may be required.

Integration Approach

Stack Fit

  • Laravel Ecosystem: Optimized for Laravel 12.x, with native support for:
    • Eloquent Models: HasFsm trait integrates with Eloquent lifecycle hooks.
    • Events/Listeners: StateTransitioned, TransitionFailed events integrate with Laravel’s event system.
    • Queues: Async actions (e.g., queuedAction) leverage Laravel Queues.
    • Enums: Uses PHP 8.1+ enums for type-safe state definitions.
  • Database: Works with any PDO-supported database (MySQL, PostgreSQL, etc.). No schema migrations required beyond the existing state column.
  • Testing: Compatible with Laravel’s testing tools (e.g., dryRun for assertions).

Migration Path

  1. Assessment Phase:
    • Audit existing state management (e.g., manual if-else checks, custom services).
    • Identify workflows with repeated state transitions (e.g., order status, user roles).
  2. Pilot Implementation:
    • Start with a non-critical model (e.g., Document for approvals).
    • Define enums and FSM definitions incrementally.
    • Test with dryRun before enabling transitions.
  3. Phased Rollout:
    • Phase 1: Replace simple state checks with FSM guards/actions.
    • Phase 2: Migrate complex workflows (e.g., order processing) with full event logging.
    • Phase 3: Extend to multiple FSMs per model if needed.
  4. Deprecation:
    • Gradually remove legacy state logic (e.g., if ($order->status === 'paid')$order->fsm()->is(OrderStatus::Paid)).

Compatibility

  • Existing Code:
    • Read Operations: Replace direct column checks with FSM methods (e.g., $order->status$order->getFsmState()).
    • Write Operations: Replace manual updates with trigger() or transitionFsm().
    • Business Logic: Refactor state-dependent logic into guards/actions/callbacks.
  • Third-Party Packages:
    • No known conflicts. The package is isolated to the Fsm namespace.
    • May integrate with Laravel Nova for UI state visualization (custom resource tools needed).

Sequencing

  1. Setup:
    • Install via Composer.
    • Publish config (php artisan vendor:publish --tag=fsm-config).
    • Configure logging/transactions as needed.
  2. Definition:
    • Create enum classes for states (e.g., OrderStatus).
    • Implement FsmDefinition classes in app/Fsm/Definitions.
  3. Model Integration:
    • Add use HasFsm to target models.
    • Define the state column (default: status).
  4. Testing:
    • Write unit tests for guards/actions using dryRun.
    • Test edge cases (e.g., invalid transitions, concurrent requests).
  5. Deployment:
    • Clear FSM cache (php artisan fsm:cache:clear).
    • Monitor TransitionFailed events in production.

Operational Impact

Maintenance

  • Pros:
    • Centralized Logic: State transitions are defined in one place (FsmDefinition), reducing duplication.
    • Type Safety: Enums prevent invalid state values at compile time.
    • Auditability: Built-in logging and events simplify debugging.
  • Cons:
    • Definition Management: FSM definitions must be version-controlled and tested rigorously. Changes to workflows require code updates.
    • Guard Complexity: Custom validation logic (guards) may need updates as business rules evolve.
    • Dependency on Package: Future maintenance relies on the package’s roadmap (currently active, but MIT license allows forks).

Support

  • Developer Onboarding:
    • Requires understanding of FSMs, Laravel events, and fluent APIs.
    • Provide a cheat sheet for common patterns (e.g., guards, async actions).
  • Runtime Issues:
    • Failed Transitions: Monitor TransitionFailed events for guard/action failures.
    • Performance: Profile logging/queue overhead in high-throughput systems.
  • Documentation:
    • The package includes PlantUML/DOT diagram generation (php artisan fsm:diagram), which is invaluable for visualizing workflows.
    • Supplement with internal runbooks for critical paths (e.g., order cancellation).

Scaling

  • Horizontal Scaling:
    • Stateless operations (e.g., trigger()) scale naturally with Laravel’s queue system.
    • Database Locks: For critical transitions, consider selectForUpdate() in guards to prevent race conditions.
  • Vertical Scaling:
    • Logging/queue performance may become a bottleneck under extreme load. Adjust event_logging.queue config to use a high-performance queue (e.g., Redis).
  • Multi-Tenancy:
    • FSM definitions are model-specific, so multi-tenant systems can share the same definitions or customize per tenant.

Failure Modes

Failure Scenario Impact Mitigation
Invalid state transition Data corruption or logic errors Use can() checks before trigger(). Enable logging.log_failures.
Guard/action throws exception Transition fails silently Listen to TransitionFailed events; implement retry logic for idempotent actions.
Database transaction rollback Partial state changes Ensure all side effects (e.g., email sends) are idempotent or use queues.
Concurrent transitions Race conditions (e.g., double payment) Use database locks or optimistic concurrency control (e.g., version columns).
Package update breaks compatibility Workflow failures Test against package updates in staging. Use feature flags for major changes.
Logging overhead Performance degradation Disable logging in production if
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony