lazerg / laravel-enum-pro
Laravel Enum Pro
v0.5.2
2024-05-04 13:07 UTC
Requires
- php: ^8.1|^8.2|^8.3
- illuminate/support: ^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
Requires (Dev)
- pestphp/pest: ^1.22|^2.0
README
最后,在 php81
中已添加对 枚举类型 的支持。但作为 PHP 中的新特性,我们没有一些辅助函数来轻松地与之交互。因此,使用我们的 enum-pro 包,您在使用枚举时比内置方法有更多选项。
它只是一个需要在枚举中添加的 trait Lazerg\LaravelEnumPro\EnumPro
。这意味着它使用内置的枚举类,同时增强其功能。
安装
composer require lazerg/laravel-enum-pro
用法
创建一个新的枚举类,并使用该 trait。
enum LevelTypes: int { use \Lazerg\LaravelEnumPro\EnumPro; case VERY_EASY = 1; case EASY = 2; case MEDIUM = 3; case STRONG = 4; case VERY_STRONG = 5 }
调用
使用默认函数,如果您想获取 case 的值,您应该编写 LevelTypes::VERY_EASY->value
,这有点长。使用我们的包,您可以通过静态调用来获取 case 的值。
LevelTypes::VERY_EASY() // 1
名称
如您所见,这里的名称为 VERY_EASY
、EASY
、MEDIUM
、STRONG
、VERY_STRONG
。要获取枚举的所有 case 名称,您可以使用这些辅助方法。
LevelTypes::names(); // Collection: ['VERY_EASY', 'EASY', 'MEDIUM', 'STRONG', 'VERY_STRONG'] LevelTypes::namesToArray(); // Array: ['VERY_EASY', 'EASY', 'MEDIUM', 'STRONG', 'VERY_STRONG'] LevelTypes::namesToString(); // String: VERY_EASY, EASY, MEDIUM, STRONG, VERY_STRONG LevelTypes::nameOf(1); // String: VERY_EASY
值
如您所见,这里的值为 1
、2
、3
、4
、5
。**常用用途**:用于验证传入的请求数据。
LevelTypes::values(); // Collection: [1, 2, 3, 4, 5] LevelTypes::valuesToArray(); // Array: [1, 2, 3, 4, 5] LevelTypes::valuesToString(); // String: 1, 2, 3, 4, 5 LevelTypes::valueOf('very easy'); // 1
随机化
有时我们需要从枚举中获取随机值或值。这在主要用在工厂中。
LevelTypes::random(int $count = 1); // Collection of $count random values LevelTypes::randomArray(int $count = 1); // Array of $count random values LevelTypes::randomFirst(); // One random value
选项
在创建管理面板时,我们通常会更改模型的状态。基本上,建议将所有状态类型保存在枚举中。因此,在管理面板中,我们需要获取枚举的所有选项用于选择。这就是为什么我们有了 options()
方法。
LevelTypes::options(); // Return collection of selectable options LevelTypes::optionsToArray(); // Return array of selectable options
选项示例
Illuminate\Support\Collection {#7777 #items: array:5 [ 1 => "Very Easy" 2 => "Easy" 3 => "Medium" 4 => "Strong" 5 => "Very Strong" ] }
选择
有时在管理面板中,以对象数组的形式提供选项更容易。为此,我们也有 selections()
方法。
LevelTypes::selections(); LevelTypes::selectionsToArray();
选择示例
Illuminate\Support\Collection {#7777 #items: array:5 [ 0 => [ "value" => "1", "display" => "Very Easy", ], 1 => [ "value" => "2", "display" => "Easy", ], 2 => [ "value" => "3", "display" => "Medium", ], 3 => [ "value" => "4", "display" => "Strong", ], 4 => [ "value" => "5", "display" => "Very Strong", ], ] }
测试
要运行测试
./vendor/bin/pest