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.
composer require paillechat/php-enum:^2.0
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;
}
$role = UserRole::ADMIN(); // Returns a singleton instance
@method PHPDoc annotations for IDE autocompletion (e.g., @method static static ADMIN).createByName() for deserialization (e.g., API responses).Strict Equality Checks:
Enums enforce strict type safety. Use === for comparisons:
if ($role === UserRole::ADMIN()) {
// ...
}
Deserialization: Convert strings/names back to enums:
$roleName = 'ADMIN';
$role = UserRole::createByName($roleName); // Case-sensitive
Type Safety in Functions: Enforce enum constraints in method signatures:
public function assignRole(UserRole $role) {
// $role is guaranteed to be a UserRole instance
}
Collection Handling: Enums work seamlessly with PHP arrays and collections:
$allowedRoles = [UserRole::ADMIN(), UserRole::EDITOR()];
if (\in_array($role, $allowedRoles, true)) {
// ...
}
status column):
class Post extends Model
{
protected $casts = [
'status' => UserRole::class, // Stores enum name as string
];
}
$response->json(['role' => $role->getName()]);
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'role' => ['required', 'in:' . implode(',', UserRole::getNames())],
]);
Case Sensitivity:
createByName() is case-sensitive. Use strtoupper() for API inputs:
$role = UserRole::createByName(strtoupper($request->input('role')));
Deprecated Methods:
Avoid equals(), __construct(), and getValue() (use ===, createByName(), and (string) cast instead).
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)
IDE Autocompletion:
Without @method PHPDoc annotations, IDEs may not suggest enum constants.
createByName() fails, verify the input matches a constant name exactly (including case).UserRole $role), not the base Enum class.Custom Logic:
Override getName() or add class methods for domain-specific behavior:
class UserRole extends Enum
{
public function isAdmin(): bool {
return $this === self::ADMIN();
}
}
Serialization:
Implement JsonSerializable for custom JSON output:
class UserRole extends Enum implements JsonSerializable
{
public function jsonSerialize() {
return ['name' => $this->getName(), 'value' => (int)$this];
}
}
Database Storage:
Use getName() for database columns (e.g., status as VARCHAR):
$post->status = UserRole::ADMIN()->getName(); // Stores 'ADMIN'
How can I help you explore Laravel packages today?