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

Php Enum Laravel Package

paillechat/php-enum

PHP 7+ enum library: define enums by extending Enum and declaring constants, then instantiate via static named calls (IssueType::ONE()). Instances are strict-equal singletons, work with in_array/type hints, and can convert to/from names.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require paillechat/php-enum:^2.0
    
  2. Declare an Enum: Create a class extending Paillechat\Enum\Enum and define protected const members.
    use Paillechat\Enum\Enum;
    
    class UserRole extends Enum
    {
        protected const ADMIN = 1;
        protected const EDITOR = 2;
        protected const VIEWER = 3;
    }
    
  3. First Use Case: Access enum values via static calls:
    $role = UserRole::ADMIN(); // Returns a singleton instance
    

Where to Look First

  • Documentation: Focus on the README for core usage patterns.
  • Type Hints: Use @method PHPDoc annotations for IDE autocompletion (e.g., @method static static ADMIN).
  • Static Methods: Prioritize createByName() for deserialization (e.g., API responses).

Implementation Patterns

Core Workflows

  1. Strict Equality Checks: Enums enforce strict type safety. Use === for comparisons:

    if ($role === UserRole::ADMIN()) {
        // ...
    }
    
  2. Deserialization: Convert strings/names back to enums:

    $roleName = 'ADMIN';
    $role = UserRole::createByName($roleName); // Case-sensitive
    
  3. Type Safety in Functions: Enforce enum constraints in method signatures:

    public function assignRole(UserRole $role) {
        // $role is guaranteed to be a UserRole instance
    }
    
  4. Collection Handling: Enums work seamlessly with PHP arrays and collections:

    $allowedRoles = [UserRole::ADMIN(), UserRole::EDITOR()];
    if (\in_array($role, $allowedRoles, true)) {
        // ...
    }
    

Integration Tips

  • Laravel Eloquent: Use enums for model attributes (e.g., status column):
    class Post extends Model
    {
        protected $casts = [
            'status' => UserRole::class, // Stores enum name as string
        ];
    }
    
  • API Responses: Serialize enums to names for JSON:
    $response->json(['role' => $role->getName()]);
    
  • Validation: Validate against allowed enums:
    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($data, [
        'role' => ['required', 'in:' . implode(',', UserRole::getNames())],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity: createByName() is case-sensitive. Use strtoupper() for API inputs:

    $role = UserRole::createByName(strtoupper($request->input('role')));
    
  2. Deprecated Methods: Avoid equals(), __construct(), and getValue() (use ===, createByName(), and (string) cast instead).

  3. Singleton Behavior: Each enum value is a singleton. Reassigning constants won’t create new instances:

    $role1 = UserRole::ADMIN();
    $role2 = UserRole::ADMIN();
    $role1 === $role2; // true (same instance)
    
  4. IDE Autocompletion: Without @method PHPDoc annotations, IDEs may not suggest enum constants.

Debugging

  • Unexpected Instances: If createByName() fails, verify the input matches a constant name exactly (including case).
  • Type Errors: Ensure method signatures accept the enum class (e.g., UserRole $role), not the base Enum class.

Extension Points

  1. Custom Logic: Override getName() or add class methods for domain-specific behavior:

    class UserRole extends Enum
    {
        public function isAdmin(): bool {
            return $this === self::ADMIN();
        }
    }
    
  2. Serialization: Implement JsonSerializable for custom JSON output:

    class UserRole extends Enum implements JsonSerializable
    {
        public function jsonSerialize() {
            return ['name' => $this->getName(), 'value' => (int)$this];
        }
    }
    
  3. Database Storage: Use getName() for database columns (e.g., status as VARCHAR):

    $post->status = UserRole::ADMIN()->getName(); // Stores 'ADMIN'
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky