关于 laravel-enums
面向 Laravel 开发的枚举指南,用枚举表示有限且类型安全的值。内容涵盖有底层值的枚举、行为与 UI 辅助方法,以及在模型、DTO、验证和队列中的用法,并说明何时选择状态机。
主要功能
- 01使用字符串或整数底层值枚举
- 02为枚举添加行为和 Trait
- 03提供标签与下拉选项数据
- 04在模型和 DTO 中使用枚举
- 05验证枚举值
- 06区分枚举与状态机
适用场景
- 01建模订单状态和支付方式
- 02验证请求中的枚举字段
- 03通过枚举值指定队列名称
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ leeovery/ claude-laravel --skill laravel-enums安装后在 Claude Code 中输入/laravel-enums确认已加载。
详细介绍
Laravel 枚举
枚举提供类型安全的有限值集合。
相关指南:
- 状态机 - 适用于复杂的状态转换
- 模型 - 将模型转换为枚举
- DTO - 包含枚举属性的 DTO
- form-requests.md - 枚举验证
始终使用有底层值的枚举
始终使用有底层值的枚举(字符串或整数):
<?php
declare(strict_types=1);
namespace App\Enums;
enum OrderStatus: string
{
case Pending = 'pending';
case Processing = 'processing';
case Completed = 'completed';
case Cancelled = 'cancelled';
}
使用 Trait 的枚举
使用 Trait 添加功能:
<?php
declare(strict_types=1);
namespace App\Enums;
use Henzeb\Enumhancer\Concerns\Comparison;
use Henzeb\Enumhancer\Concerns\Dropdown;
enum OrderStatus: string
{
use Comparison, Dropdown;
case Pending = 'pending';
case Processing = 'processing';
case Completed = 'completed';
case Cancelled = 'cancelled';
}
带标签的枚举
<?php
declare(strict_types=1);
namespace App\Enums;
use App\Enums\Attributes\Label;
use App\Enums\Concerns\HasLabel;
enum PaymentMethod: string
{
use HasLabel;
#[Label('Credit Card')]
case CreditCard = 'credit-card';
#[Label('Bank Transfer')]
case BankTransfer = 'bank-transfer';
#[Label('PayPal')]
case PayPal = 'paypal';
}
自定义枚举属性
<?php
declare(strict_types=1);
namespace App\Enums\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS_CONSTANT)]
class Label
{
public function __construct(public string $value) {}
}
#[Attribute(Attribute::TARGET_CLASS_CONSTANT)]
class Color
{
public function __construct(public string $value) {}
}
#[Attribute(Attribute::TARGET_CLASS_CONSTANT)]
class Icon
{
public function __construct(public string $value) {}
}
枚举关注点
<?php
declare(strict_types=1);
namespace App\Enums\Concerns;
use App\Enums\Attributes\Label;
use Henzeb\Enumhancer\Concerns\Attributes;
use Henzeb\Enumhancer\Concerns\Dropdown;
use Henzeb\Enumhancer\Concerns\Labels;
trait HasLabel
{
use Attributes, Dropdown, Labels;
public static function labels(): array
{
return collect(self::cases())->mapWithKeys(fn ($enum) => [
$enum->name => $enum->getLabel(),
])->toArray();
}
public function getLabel(): ?string
{
return $this->getAttribute(Label::class)?->value;
}
}
枚举中的业务逻辑
枚举可以包含行为:
enum PaymentProvider: string
{
case Stripe = 'stripe';
case PayPal = 'paypal';
case Square = 'square';
public function processingFee(int $amount): int
{
return match ($this) {
self::Stripe => (int) ($amount * 0.029 + 30),
self::PayPal => (int) ($amount * 0.034 + 30),
self::Square => (int) ($amount * 0.026 + 10),
};
}
public function supportsRefunds(): bool
{
return match ($this) {
self::Stripe, self::PayPal => true,
self::Square => false,
};
}
}
在模型中的用法
protected function casts(): array
{
return [
'status' => OrderStatus::class,
'payment_method' => PaymentMethod::class,
];
}
在 DTO 中的用法
public function __construct(
public OrderStatus $status,
public PaymentMethod $paymentMethod,
) {}
在验证中的用法
use Illuminate\Validation\Rules\Enum;
'status' => [
'required',
'string',
'bail',
new Enum(OrderStatus::class),
],
常见模式
比较
if ($order->status->is(OrderStatus::Completed)) {
// ...
}
// With enumhancer Comparison trait
if ($order->status->isCompleted()) {
// ...
}
UI 属性
$status->getLabel(); // 'Completed'
PaymentMethod::dropdown(); // For select inputs
OrderStatus::labels(); // All labels as array
Match 表达式
$message = match ($order->status) {
OrderStatus::Pending => 'Your order is pending',
OrderStatus::Processing => 'We are processing your order',
OrderStatus::Completed => 'Your order is complete',
OrderStatus::Cancelled => 'Your order was cancelled',
};
队列枚举示例
<?php
declare(strict_types=1);
namespace App\Enums;
enum Queue: string
{
case Default = 'default';
case Processing = 'processing';
case Emails = 'emails';
case Notifications = 'notifications';
}
在作业中的用法:
public function __construct(public Order $order)
{
$this->onQueue(Queue::Emails->value);
}
目录结构
app/Enums/
├── OrderStatus.php
├── PaymentMethod.php
├── Queue.php
├── Attributes/
│ ├── Label.php
│ ├── Color.php
│ └── Icon.php
└── Concerns/
└── HasLabel.php
何时使用枚举与状态机
使用枚举:
- 简单的状态字段
- 没有转换逻辑
- 没有副作用
使用状态机:
- 带规则的复杂状态转换
- 特定状态的行为
- 转换副作用
有关状态机,请参阅状态机。
总结
枚举提供:
- 类型安全
- 有限值集合
- 业务逻辑封装
- UI 辅助功能(标签、颜色、图标)
- IDE 自动补全
始终使用有底层值的枚举,其值为字符串或整数。
评论
支持 Markdown