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

Enumata Laravel Package

norotaro/enumata

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • State Machine Pattern Alignment: The package leverages state machines for Eloquent models, which is a natural fit for workflows with discrete, transition-based states (e.g., order processing, user onboarding, content moderation).
  • Enum-Driven Design: Uses PHP enums (introduced in PHP 8.1+) to define states and transitions, reducing magic strings and improving type safety.
  • Laravel Eloquent Integration: Tightly couples with Laravel’s ORM, enabling seamless database persistence and query filtering (e.g., whereState()).
  • Domain-Specific Constraints: Ideal for domains where state transitions must adhere to strict business rules (e.g., "a payment can’t be refunded after completion").

Integration Feasibility

  • Low Friction for Laravel Apps: Requires minimal boilerplate—define states in an enum file, attach to a model, and implement transitions.
  • Database Agnostic: Works with any Eloquent-supported database (MySQL, PostgreSQL, SQLite).
  • Event Hooks: Supports transition events (e.g., stateChanged), enabling integration with Laravel’s event system (e.g., broadcasting, notifications).
  • Validation Layer: Built-in transition validation prevents invalid state changes (e.g., throwing TransitionNotAllowedException).

Technical Risk

  • PHP 8.1+ Dependency: Requires PHP 8.1+ (enums) and Laravel 9+ (for illuminate/support compatibility). Risk: Legacy systems may need upgrades.
  • Enum Overhead: Enums add compile-time safety but may introduce complexity for simple state machines.
  • Transition Logic Centralization: Custom transition logic (e.g., pre/post-transition checks) must be defined in the model or enum, which could scatter business rules.
  • Testing Complexity: State machines require exhaustive transition testing (e.g., edge cases, invalid paths). Risk: Undiscovered invalid transitions in production.
  • Performance: State transitions trigger database writes (if using save()). Risk: High-frequency transitions (e.g., real-time systems) may impact performance.

Key Questions

  1. State Complexity: Does the domain require hierarchical states (e.g., nested workflows) or simple linear transitions? Enumata supports flat state machines by default.
  2. Concurrency Control: How are concurrent state changes handled (e.g., race conditions on transitions)? The package lacks built-in optimistic/pessimistic locking.
  3. Auditability: Are state changes logged for compliance? The package doesn’t include built-in audit trails (would require custom middleware).
  4. Migration Strategy: How will existing stateful models (e.g., with raw status columns) migrate to enums? Backfilling enums may require downtime.
  5. Third-Party Integrations: Are there external systems (e.g., queues, APIs) that need to react to state changes? Event listeners or webhooks may be needed.
  6. Custom Transition Logic: Can complex pre/post-transition logic (e.g., API calls, notifications) be encapsulated without bloating the model?
  7. Fallback States: How are invalid transitions handled in production? The package throws exceptions, but UI/CLI fallbacks may be needed.

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfect for Laravel applications using Eloquent. Complements packages like:
    • Spatie Laravel Activitylog (for auditing transitions).
    • Laravel Events (for broadcasting state changes).
    • Laravel Nova/Panel (for state-aware UIs).
  • PHP 8.1+: Requires modern PHP features (enums, attributes). Mitigation: Upgrade PHP if using older versions.
  • Database: Works with any Eloquent-supported database. Note: State values are stored as strings in the DB (enum-backed).

Migration Path

  1. Assess Current State Management:
    • Audit existing models with ad-hoc state logic (e.g., if ($model->status === 'pending')).
    • Identify models where state transitions are critical (prioritize these for migration).
  2. Define Enums:
    • Create enum files for each stateful model (e.g., OrderStatus.php).
    • Example:
      enum OrderStatus: string {
          case PENDING = 'pending';
          case PROCESSING = 'processing';
          case COMPLETED = 'completed';
          case CANCELLED = 'cancelled';
      
          public function transitions(): array {
              return [
                  self::PENDING => [self::PROCESSING, self::CANCELLED],
                  self::PROCESSING => [self::COMPLETED, self::CANCELLED],
              ];
          }
      }
      
  3. Attach to Models:
    • Use the HasStates trait and configure the enum class:
      use Norotaro\Enumata\HasStates;
      
      class Order extends Model {
          use HasStates;
      
          protected $stateEnum = OrderStatus::class;
      }
      
  4. Implement Transitions:
    • Override transition() in the model for custom logic:
      public function transitionToProcessing(): void {
          $this->transition(OrderStatus::PROCESSING);
          // Custom logic (e.g., dispatch event, update inventory)
      }
      
  5. Update Queries/Views:
    • Replace raw WHERE status = 'pending' with whereState(OrderStatus::PENDING).
    • Update UI components to use enum values (e.g., <select> options).

Compatibility

  • Laravel Versions: Tested with Laravel 9+. Compatibility Matrix:
    Laravel Version PHP Version Compatible?
    9.x 8.1+ ✅ Yes
    10.x 8.1+ ✅ Yes
    11.x 8.2+ ✅ Yes
    8.x 7.4+ ❌ No (enums)
  • Database: No schema changes required (uses existing columns). Note: Ensure the column type can store enum string values (e.g., VARCHAR).
  • Testing: Requires PHPUnit. Mitigation: Add transition test cases to existing test suites.

Sequencing

  1. Phase 1: Pilot Model
    • Start with a low-risk model (e.g., UserSubscription).
    • Implement enum, transitions, and basic queries.
    • Validate with manual tests and a small user group.
  2. Phase 2: Core Workflows
    • Migrate high-impact models (e.g., Order, Ticket).
    • Integrate with events/notifications.
  3. Phase 3: UI/CLI Updates
    • Update admin panels, APIs, and CLI commands to use enums.
  4. Phase 4: Deprecation
    • Deprecate old state logic (e.g., if ($order->status === 'pending')).
    • Add deprecation warnings in CI.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: State transitions are centralized in enums/models.
    • Type Safety: Enums catch invalid states at compile time.
    • Consistent Validation: Transition rules are enforced by the package.
  • Cons:
    • Enum Management: Adding/removing states requires enum file updates and potential DB migrations.
    • Testing Burden: Each transition path must be tested (e.g., "Can a PROCESSING order skip to COMPLETED?").
    • Dependency Risk: Package updates may introduce breaking changes (e.g., new exception types).

Support

  • Debugging:
    • Transition Failures: Clear exceptions with context (e.g., "Cannot transition from PENDING to COMPLETED").
    • State Queries: Debugging whereState() filters may require understanding enum values.
  • Documentation:
    • Gaps: Limited real-world examples in the README. Mitigation: Create internal docs with:
      • Enum design patterns (e.g., hierarchical states).
      • Common transition pitfalls (e.g., circular dependencies).
  • Community:
    • Low Adoption: 3 stars/0 dependents may indicate niche use. Mitigation: Engage with Laravel Discord/Forums for feedback.

Scaling

  • Performance:
    • Database Load: Each transition triggers a save(), which may not scale for high-frequency state changes (e.g., WebSocket-driven updates).
      • Mitigation: Use database transactions or batch transitions.
    • Enum Lookups: Enums are in-memory; no performance impact at scale.
  • Concurrency:
    • Race Conditions: No built-in locking. Risk: Two concurrent transitions could corrupt state.
      • Mitigation: Use Laravel’s databaseTransactions or optimistic locking ($model->fresh()).
  • Horizontal Scaling:
    • Stateless transitions work well in distributed systems. Note: Ensure event listeners (e.g., for notifications) are idempotent.

Failure Modes

Failure Scenario Impact Mitigation Strategy
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver