dilovanmatini/laravel-enumable
Composer 安装命令:
composer require dilovanmatini/laravel-enumable
包简介
The Laravel Enumable trait provides a set of utility methods to enhance PHP enums. It includes methods for manipulating enum cases, retrieving labels, and converting enums to various formats.
README 文档
README
Native PHP enums with Laravel-friendly helpers for labels, selects, validation, and case filtering.
Overview
The Enumable trait enhances backed PHP enums (string or int) with utilities for forms, APIs, and validation—without replacing native enums.
Installation
composer require dilovanmatini/laravel-enumable
No service provider or configuration is required.
Upgrading from 1.0.x? See UPGRADE.md.
Requirements
- PHP 8.1 or higher (Laravel 13 applications require PHP 8.3+)
- Laravel 10, 11, 12, or 13
Usage
use DilovanMatini\Enumable\Traits\Enumable; enum Status: string { use Enumable; case Draft = 'draft'; case Published = 'published'; }
Methods
Class methods
| Method | Description |
|---|---|
values() |
All backed values |
names() |
All case names |
labels() |
[value => label] |
toSelectArray() |
Alias of labels() |
toSelectArrayByName() |
[name => label] |
toArray() |
[value => name] |
toCollection() |
Laravel collection of cases |
getCase($value) |
Resolve by value (tryFrom for backed enums) |
tryFromValue($value) |
Alias of getCase() |
fromName($name) |
Resolve by case name |
fromNameOrDefault($name) |
Resolve by name or fall back to default() |
getName($value) |
Case name for a value |
getLabel($value) |
Label for a value |
exists($value) |
Whether value, name, or case exists |
random() |
Random case |
default() |
Default case (override in your enum) |
first() / last() |
First or last case |
count() |
Number of cases |
only($cases) |
Filtered subset (full Enumable API) |
except($cases) |
Inverse filtered subset |
generate($cases) |
Build a filtered subset |
rule() |
Laravel Rule::enum() |
ruleOnly($cases) |
Rule::in() for a subset |
ruleExcept($cases) |
Rule::in() excluding cases |
Instance methods
| Method | Description |
|---|---|
label() |
Human-readable label |
headline() |
Headline from case name |
trans($key, $replace, $locale) |
Translation helper |
is($other) |
Compare to case, value, or name |
isAny($others) |
True if any match |
in($others) |
Alias of isAny() |
str($label = false) |
String helpers (camel, slug, etc.) |
Examples
// Lists & selects Status::values(); // ['draft', 'published'] Status::labels(); // ['draft' => 'Draft', 'published' => 'Published'] Status::toSelectArray(); // same as labels() // Resolution Status::getCase('draft'); // Status::Draft Status::fromName('Draft'); // Status::Draft // Validation (Form Request) Status::rule(); Status::ruleOnly(['draft', 'published']); // Filtering (subset supports static and instance calls, same as 1.0.x) Status::except(['draft'])::labels(); Status::only([Status::Published])->cases(); // Instance helpers Status::Draft->label(); Status::Draft->str()->slug(); // "draft" Status::Draft->is('draft'); // true
Custom labels
Prefer labelsMap() (or keep using setLabels() for backward compatibility):
public static function labelsMap(): array { return [ self::Draft->value => 'Draft (hidden)', self::Published->value => 'Live', ]; }
Default case
Override default() on your enum:
public static function default(): self { return self::Draft; }
Blade select
<select name="status"> @foreach (Status::toSelectArray() as $value => $label) <option value="{{ $value }}">{{ $label }}</option> @endforeach </select>
Eloquent
Use Laravel's native enum casting:
protected $casts = [ 'status' => Status::class, ];
Backed enums only
Methods that rely on a backed value (values(), labels(), only(), etc.) require string or int backed enums. Unit enums support name-based helpers such as fromName() and exists() by name.
Migrating from BenSampo/laravel-enum
| BenSampo | Enumable |
|---|---|
getValue() |
$case->value |
getDescription() |
$case->label() |
toSelectArray() |
toSelectArray() or labels() |
coerce() |
tryFromValue() or getCase() |
Comparison with Other Enum Packages
| Feature / Package | Laravel Enumable (this package) | BenSampo\Enum | Native PHP Enums |
|---|---|---|---|
| Laravel Version Support | 9.x, 10.x, 11.x, 12.x, 13.x (with illuminate/* deps) |
8.x, 9.x, 10.x, 11.x | Laravel 9+ (for PHP 8.1+ enums) |
| Enum Backing | Native PHP 8.1+ enums | Class-based emulation pre-8.1, native post-8.1 | Native |
| Get All Cases/Values/Names | ✔️ cases(), names(), values() | ✔️ getValues(), getNames(), getInstances() | ✔️ cases() |
| Labeling/Custom Labels | ✔️ labels(), setLabels(), labelsMap() (+translate) | ✔️ description, custom labels via method | Manual implementation |
| Array/Map Conversion | ✔️ toArray(), toSelectArray(), toSelectArrayByName() | ✔️ asArray(), asSelectArray() | Manual (array_map/cases) |
| Validation Rules | ✔️ rule(), ruleOnly(), ruleExcept(), integrate w/Validator | ✔️ validationRule() | Manual |
| Lookup Helpers | ✔️ tryFromValue(), fromName(), fromNameOrDefault() | ✔️ coerce(), fromKey(), fromValue(), etc. | Native tryFrom()/from() (limited) |
| Comparison & In Checks | ✔️ is(), isAny(), in() | ✔️ isOneOf() | Manual or custom |
| String Helpers | ✔️ str(), slug(), snake(), camel(), etc. via EnumStringable | ❌ | ❌ |
| Translation Support | ✔️ trans(), translation key helpers | ❌ | Manual |
| Subset/Filtering | ✔️ only(), except(), generate() | ✔️ filter() | Manual |
| Macroable/Extendability | ❌ (not macroable, but adds helpers) | ✔️ Macroable (extend enum classes) | Manual |
| Test/Type Coverage | ✔️ (PHPStan level 8, extensive tests) | Good | N/A |
| Zero Config (out-of-the-box) | ✔️ | ❌ (service provider if using Laravel integration) | ✔️ (once enum is defined) |
| Extra Features | EnumStringable (String inflection), advanced labels | Enum annotations, custom casting, traits | N/A |
Legend: ✔️ = Supported; ❌ = Not Supported; Manual = Can be achieved but requires additional code.
Last reviewed: Laravel Enumable v1.1.0, BenSampo\Enum v5.x, PHP 8.1+ enums.
Changelog
See CHANGELOG.md for release notes.
License
MIT © Dilovan Matini
dilovanmatini/laravel-enumable 适用场景与选型建议
dilovanmatini/laravel-enumable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.89k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2024 年 08 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「enum」 「laravel」 「php-enum」 「dilovanmatini」 「enumable」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 dilovanmatini/laravel-enumable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 dilovanmatini/laravel-enumable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 dilovanmatini/laravel-enumable 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Enum type behavior for Yii2 based on class constants
A symfony bundle to serialize/deserialize enumerations of type myclabs/php-enum with jms/serializer
Enum Component
A PHP Abstract Enum Class
Compatibility layer for emulating enumerations in PHP < 8.1 and native enumerations in PHP >= 8.1
Better PHP enum support
统计信息
- 总下载量: 2.89k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 9
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-08-10