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

Typed Enum Laravel Package

laudis/typed-enum

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Type Safety: Eliminates runtime errors from magic strings or typos (e.g., Foo::BAR vs. Foo::bar) by enforcing strict typing via TypedEnum. Aligns with Laravel’s push toward stricter typing (e.g., PHP 8+ features).
    • Singleton Pattern: Guarantees a single instance per value, preventing accidental duplication and ensuring referential equality (===).
    • IDE and Static Analysis Support: Works seamlessly with PHPStorm, VSCode, and tools like Psalm/PHPStan, improving developer productivity and code quality. The @method annotations and Psalm integration (@extends TypedEnum<string>) enable autocompletion and static type checking.
    • Lightweight and Decoupled: Minimal overhead (~1KB) and no framework-specific dependencies, making it easy to adopt incrementally.
    • Versatile Value Types: Supports scalar values (strings, integers, floats), covering most use cases for domain modeling (e.g., OrderStatus::PENDING, PriorityLevel::HIGH).
    • Resolve Functionality: The resolve() method allows reverse lookups (value → enum), which is useful for validation, serialization, and deserialization scenarios.
  • Cons:

    • Not Native to PHP: Requires explicit class inheritance (extends TypedEnum), which may feel less idiomatic compared to PHP 8.1+ native enums. This could lead to slight cognitive overhead for developers unfamiliar with the pattern.
    • Limited to Scalar Values: Cannot natively handle complex objects or arrays as enum values, which might be a limitation for advanced use cases (though workarounds like json_encode/json_decode could be implemented).
    • No Built-in Serialization: Requires manual handling for JSON/API responses (e.g., getValue() + custom serialization logic). This could add boilerplate for APIs or cached data.
    • Static Nature: Enums are defined at class level and cannot be dynamically generated at runtime, which might be a limitation for highly dynamic systems.

Integration Feasibility

  • Laravel Compatibility:

    • Dependency Injection: Enums can be type-hinted in constructors, services, and controllers, integrating smoothly with Laravel’s IoC container.
    • Validation: Works seamlessly with Laravel’s validation rules (e.g., Rule::in([UserRole::ADMIN->value, UserRole::EDITOR->value])).
    • Eloquent Models: Enums can be used as model attributes, with support for casting and accessors to handle serialization/deserialization.
    • Artisan Commands and API Resources: Enums can be used to define consistent responses and command options, improving maintainability.
    • Testing: Enables exhaustive testing of enum cases and strict equality checks, reducing flaky tests tied to loose comparisons or magic strings.
  • Testing and Debugging:

    • Unit Testing: Enums support strict equality checks (===) and value resolution, making it easier to write reliable tests.
    • Static Analysis: Psalm and PHPStan can verify enum usage and catch invalid cases early in the development cycle.

Technical Risk

  • Migration Risk:

    • Low for Greenfield Projects: Easy to adopt in new projects where magic strings are not deeply embedded.
    • Moderate for Legacy Codebases: Requires refactoring to replace existing magic strings with enums, which may involve database migrations (e.g., adding value columns) and API contract changes.
    • Backward Compatibility: Existing code that relies on magic strings may break if not carefully refactored. A phased migration strategy is recommended.
  • Performance:

    • Minimal Overhead: Enums are singletons, and the resolve() method uses a static map, so performance impact is negligible for typical use cases.
    • Memory Usage: Each enum instance is cached, but the memory footprint is minimal and unlikely to be a concern.
  • Tooling and IDE Support:

    • IDE Autocompletion: Requires @method annotations for full autocompletion support, which adds a small setup overhead.
    • Static Analysis: Psalm and PHPStan will catch invalid enum usage, but this requires initial configuration and developer awareness.
  • Edge Cases:

    • Duplicate Values: The resolve() method returns an array if multiple enums share the same value, which could lead to unexpected behavior if not handled carefully. Design enums to avoid duplicate values where possible.
    • Case Sensitivity: String enums are case-sensitive (e.g., 'Admin''admin'), which could cause issues if not accounted for in input validation.
    • Serialization: Requires manual handling for JSON/API responses, which could add complexity to serialization/deserialization logic.

Key Questions

  1. Enum Design and Scope:

    • Should enums be globally accessible (e.g., App\Enums\UserRole) or namespace-scoped (e.g., App\Models\User\Role) to avoid naming collisions?
    • How will enums interact with database migrations (e.g., storing value vs. enum class name or ID)?
    • Should enums be immutable (final classes) or allow for extensions (e.g., adding new values in child classes)?
  2. Backward Compatibility:

    • How will existing codebases handle the transition from magic strings to enums, especially in API contracts, configuration files, and database records?
    • Should a deprecation strategy be implemented for magic strings (e.g., using Laravel’s deprecated helper)?
  3. Serialization and API Contracts:

    • Should enums serialize to their raw values (e.g., {"status": "pending"}) or class names (e.g., {"status": "App\Enums\UserStatus::PENDING"})?
    • How will enums be handled in OpenAPI/Swagger documentation and API responses?
  4. Testing Strategy:

    • Should tests verify enum exhaustiveness (e.g., ensuring all possible values are covered and no unused cases exist)?
    • How will factories (e.g., Laravel’s Faker) generate enum values for testing and seeding?
  5. Performance and Scaling:

    • For high-throughput systems, could the resolve() method become a bottleneck? (Unlikely, but worth profiling in performance-critical paths.)
    • Should enums be cached globally (e.g., in AppServiceProvider) to optimize repeated lookups?
  6. Alternatives and Future-Proofing:

    • Should the team wait for PHP 8.1+ native enums if upgrading is feasible, given that native enums offer similar functionality with less boilerplate?
    • Are there Laravel-specific packages (e.g., spatie/enum, nunomaduro/collision) that offer additional features or better integration with the framework?
    • How will this package interact with Laravel’s upcoming features, such as improved type support in future versions?

Integration Approach

Stack Fit

  • PHP/Laravel Ecosystem:

    • Perfect Fit for Laravel: Aligns with Laravel’s type-safety goals and integrates seamlessly with its features, such as dependency injection, validation, Eloquent models, and API resources.
    • Works with Micro-Frameworks: Compatible with Lumen and can be used in Livewire for frontend state management.
    • Build Tools: Enums can define constants for Laravel Mix/Vite, enabling type-safe configuration for frontend assets (e.g., theme options, feature flags).
  • Third-Party Libraries and Services:

    • API Platforms: Enums can replace enum types in OpenAPI/Swagger documentation, ensuring consistent API contracts.
    • Payment and Billing: Define enums for PaymentStatus, SubscriptionPlan, or InvoiceType to enforce valid states in financial workflows.
    • Search and Filtering: Use enums for faceted search in ScoutDB/Algolia or database queries (e.g., whereIn('status', OrderStatus::cases()->pluck('value'))).
    • Caching: Enums can be used to define cache keys or tags (e.g., Cache::tags([UserRole::ADMIN->value])).
  • Testing Frameworks:

    • Pest/PHPUnit: Enums enable strict equality checks and exhaustive testing of all possible values (e.g., expect(UserRole::ADMIN)->toBe(UserRole::resolve('admin')[0])).
    • Dusk/Cypress: Enums can drive UI assertions and test data generation (e.g., assertSelectOptionIsSelected('role', UserRole::ADMIN->value)).

Migration Path

  1. Phase 1: Adoption in New Code
    • Start with High-Impact Domains: Focus on enums for critical workflows (e.g., UserRole, OrderStatus, PaymentMethod) where type safety is most valuable.
    • Replace Magic Strings: Use IDE refactoring tools (e.g., "Rename" or "Find Usages") to replace magic strings with enums in:
      • Controller methods and service classes.
      • Database queries (e.g., `where('status', OrderStatus::PEND
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity