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

Enum Mapper Laravel Package

adrenalinkin/enum-mapper

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The package addresses a common pain point in PHP/Laravel applications where native database ENUM types are either unavailable (e.g., PostgreSQL supports them, but MySQL does not consistently) or where developers prefer business-logic-driven enums over database-level constraints. It maps well to domain-driven design (DDD) patterns, where enums represent bounded contexts (e.g., OrderStatus, UserRole).
  • Laravel Synergy: Laravel’s Eloquent ORM and validation layers can leverage this package to enforce type safety and human-readable values without coupling to database-specific features. Example: Replace raw string comparisons ($user->role === 'ADMIN') with typed enums ($user->role->isAdmin()).
  • Alternatives Comparison:
    • Native PHP Enums (PHP 8.1+): This package predates PHP 8.1’s built-in enums, offering backward compatibility. However, modern Laravel apps should evaluate migrating to native enums for performance and type safety.
    • Database ENUMs: Less portable across databases (e.g., MySQL vs. PostgreSQL) and harder to refactor.
    • Magic Getters/Setters: The package’s fromDatabase()/toDatabase() methods centralize conversion logic, reducing boilerplate compared to manual implementations.

Integration Feasibility

  • Low-Coupling Design: The package is stateless and agnostic to Laravel’s ecosystem, making it easy to adopt incrementally. Key integration points:
    • Model Attributes: Replace raw column values with enum instances (e.g., $user->role = new UserRole('ADMIN')).
    • Validation: Integrate with Laravel’s FormRequest or Validator to enforce allowed enum values.
    • API Responses: Serialize enums to human-readable strings in JSON (e.g., {"status": "PENDING"}).
  • Database Agnostic: Works with any database backend, though performance implications should be tested for high-write workloads (see Operational Impact).
  • Testing: Unit-testable in isolation; mock database values to verify conversions.

Technical Risk

  • Backward Compatibility:
    • Database Schema: If the app relies on ENUM types in migrations, dropping them to use strings may require schema changes. Mitigate by using a migration to alter columns to VARCHAR first.
    • Legacy Code: Search/replace raw string comparisons (e.g., if ($status == 'ACTIVE')) with enum methods (e.g., $status->isActive()). Use IDE refactoring tools or static analysis (e.g., PHPStan).
  • Performance Overhead:
    • Serialization: Converting between database values and enum objects adds minor overhead. Benchmark critical paths (e.g., bulk inserts/updates).
    • Memory: Storing enum objects in collections (e.g., User::all()) may increase memory usage. Profile with tools like Blackfire.
  • Type Safety:
    • Without PHP 8.1+, the package relies on runtime checks. Pair with Laravel’s strict_types=1 and IDE autocompletion to reduce risks.
  • Maintenance Debt:
    • Enum Evolution: Adding/removing enum values requires updating the mapper class. Document this as a breaking change in your changelog.
    • Package Abandonment: With only 1 star and no recent activity, evaluate maintaining a fork or migrating to native enums long-term.

Key Questions

  1. Why not native PHP enums?
    • Are you constrained to PHP <8.1? If not, native enums offer better type safety and performance.
    • Does the package add value beyond enum + custom toString()/from() methods?
  2. Database Schema Strategy:
    • Will you store enums as strings or integers? Strings are more flexible but may require indexing strategies.
    • How will you handle existing data during migration?
  3. Validation Layer:
    • How will this integrate with Laravel’s Rule::in() or custom validation rules?
  4. Internationalization:
    • Does the package support locale-specific enum labels? If not, will you need to extend it?
  5. Testing Strategy:
    • How will you test enum conversions in CI? Mock database values or use a test database?
  6. Long-Term Roadmap:
    • What’s the plan if you upgrade to PHP 8.1+? Will you sunset this package?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Eloquent Models: Replace raw column access with enum properties. Example:
      class User extends Model {
          protected $casts = [
              'role' => EnumMapper::class, // Hypothetical; package may need custom casting.
          ];
      }
      
    • Form Requests: Use the package to validate enum inputs:
      public function rules() {
          return [
              'status' => ['required', Rule::in(array_column(OrderStatus::cases(), 'value'))],
          ];
      }
      
    • API Resources: Transform enums to JSON:
      public function toArray($request) {
          return [
              'status' => $this->status->toHuman(),
          ];
      }
      
  • Non-Laravel PHP:
    • Works in any PHP 7.4+ app, but Laravel’s ORM/validation layers amplify its utility.
  • Frontend Integration:
    • Expose enum values via API to populate dropdowns (e.g., GET /api/statuses returns ["PENDING", "APPROVED"]).

Migration Path

  1. Assessment Phase:
    • Audit codebase for raw string comparisons tied to enums (e.g., if ($user->status == 'active')).
    • Identify critical paths (e.g., payment processing, user roles) where enum validation is needed.
  2. Incremental Adoption:
    • Step 1: Create a base EnumMapper class (or extend the package) for a single enum (e.g., OrderStatus).
    • Step 2: Update models to use the mapper for getters/setters:
      public function getStatusAttribute($value) {
          return OrderStatus::fromDatabase($value);
      }
      public function setStatusAttribute($value) {
          $this->attributes['status'] = OrderStatus::toDatabase($value);
      }
      
    • Step 3: Replace validation logic to use enum values:
      // Before
      if (!in_array($request->status, ['pending', 'approved'])) { ... }
      
      // After
      if (!$this->status->isValid()) { ... }
      
  3. Database Migration:
    • If using strings, alter columns to VARCHAR with sufficient length (e.g., ENUM in MySQL maxes at 64 chars).
    • For existing data, use a migration to convert values:
      DB::table('orders')->update([
         'status' => DB::raw("CASE status
             WHEN 'pending' THEN 'PENDING'
             WHEN 'approved' THEN 'APPROVED'
             ELSE status END"),
      ]);
      
  4. Testing:
    • Write unit tests for enum conversions (database → object → human-readable).
    • Test edge cases: invalid database values, nulls, empty strings.

Compatibility

  • Laravel Versions:
    • Tested with Laravel 8+ (PHP 7.4+). For Laravel 9/10, ensure no breaking changes with newer PHP features.
    • Compatibility with Laravel’s casts property may require custom logic (package may not support it out-of-the-box).
  • Database Drivers:
    • Works with MySQL, PostgreSQL, SQLite, etc., but test ENUM-like behavior (e.g., PostgreSQL’s text vs. MySQL’s ENUM).
  • Third-Party Packages:
    • Validation: Conflicts unlikely, but ensure enum values align with packages like spatie/laravel-permission.
    • ORM: No known conflicts with Eloquent, but test with complex relationships (e.g., polymorphic enums).

Sequencing

  1. Low-Risk First:
    • Start with non-critical enums (e.g., User::preferences) before core logic (e.g., Order::status).
  2. Critical Path Last:
    • Delay enums tied to business rules (e.g., Payment::status) until the pattern is proven stable.
  3. Feature Flags:
    • Use Laravel’s config or environment variables to toggle enum behavior during migration.
  4. Rollback Plan:
    • Maintain a backup of raw string comparisons if the migration stalls.
    • Document how to revert database schema changes.

Operational Impact

Maintenance

  • Enum Management:
    • Pros: Centralized logic for enum values reduces duplication. Changes to allowed values require updates in one place (the mapper class).
    • Cons: Adding/removing enums requires:
      • Updating the mapper class.
      • Migrating database values (if schema changes).
      • Updating frontend/API contracts.
    • Mitigation: Use feature flags for new enums until all systems are updated.
  • Deprecation:
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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