myclabs/php-enum
myclabs/php-enum brings SplEnum-style enums to PHP. Define enum classes, get autogenerated static constructors, validate values, compare instances, list possible values, and use enums as parameter/return types with extra methods—without a PHP extension.
Install the package with composer require myclabs/php-enum. Start by defining enums as final classes extending MyCLabs\Enum\Enum, using private constants for values (e.g., private const VIEW = 'view';). Use PHPDoc @method annotations for IDE autocomplete (e.g., @method static Action VIEW()), or implement static methods manually if stricter completion is needed. Use the enum as a type hint (function setAction(Action $action)) and instantiate via Action::VIEW() or new Action('view').
OrderStatus::PENDING, ShippingMethod::EXPRESS) with typed enums for method signatures and validation.public function label(): string { return match($this->getValue()) { 'pending' => 'Awaiting Payment', ... }; }).from($value) to convert request/query parameters into typed enums; rely on isValid() for safe validation before coercion.MyCLabsEnumParamConverter) to auto-resolve enums from route parameters or form data.toArray(), values(), and search() to generate fixtures, validate dropdowns, or debug payloads.Action::VIEW() → Action::VIEW, ->getValue() → ->value, == → ===, keys() → ->name). The package includes an official migration guide.Action::VIEW() are magically added via __callStatic()—they won’t show in IDEs without @method annotations. Use PhpStorm’s native support or redeclare static methods.final) to add values, but this breaks type safety in tight contracts—prefer composition over inheritance.?Action type hints or define null as a valid constant (though not recommended).JsonSerializable out-of-the-box—json_encode($enum) yields the scalar value (e.g., "view"), not an object.from() for forward compatibility with native enums. Ensure ext-json is installed—missing JSON extension causes runtime failures (fixed in 1.6.6+).@extends Enum<Action::*> and @phpstan-assert annotations (or use PHP 8.2+ native Pure attributes in newer versions) for precise static analysis. Avoid manual @template annotations (renamed in 1.7.6+ to prevent conflicts).How can I help you explore Laravel packages today?