daverandom/enum
daverandom/enum adds a lightweight enum implementation for PHP, providing type-safe sets of named values with strict validation and easy comparison. Useful for replacing magic numbers/strings in domain models, configs, and APIs.
This package provides a simple base class for defining enumerations in PHP. To get started:
composer require daverandom/enumDaveRandom\Enum class for your enum typesMyEnum::valueOf($value) or MyEnum::fromString($value)First use case: Model status constants in a clean, type-safe way instead of raw strings or ints.
use DaveRandom\Enum;
class OrderStatus extends Enum
{
const PENDING = 'pending';
const SHIPPED = 'shipped';
const DELIVERED = 'delivered';
}
$status = OrderStatus::valueOf('pending'); // returns instance of OrderStatus
PaymentMethod, UserRole, MediaType)::isValid($value) and ::getAll() for validation and dropdown population__construct() only for custom logic (rarely needed)=== for comparison (enum instances are immutable and singleton per value)myclabs/php-enum or native-backed enums in PHP 8.1+valueOf() throws an exception for invalid values — wrap calls with try/catch or use isValid() firstPENDING = 'Pending' will not match input 'pending'self will return new instances if reassignment occurs (though this class uses string-based singleton caching internally)@return OrderStatus) help IDEs but don’t enforce type safety at runtime beyond comparisonsjsonSerialize() to return the underlying scalar value ($this->getValue())How can I help you explore Laravel packages today?