konulov/interact-with-enum

用于方便使用PHP中的ENUM的特质

1.0.0 2023-06-28 19:30 UTC

This package is auto-updated.

Last update: 2024-09-07 06:34:23 UTC


README

Latest Version on Packagist Licence Total Downloads

此包包含 InteractWithEnum.php 特质,您可以使用它方便地处理ENUM。

要求

  • php: >=8.1

安装

通过Composer安装包

# Install interact-with-enum
composer require kongulov/interact-with-enum

用法

想象您有一个ENUM StatusEnum.php,其中已经使用了 InteractWithEnum 特质

<?php

namespace App\Enums;

use Kongulov\Traits\InteractWithEnum;

enum StatusEnum: string {
    use InteractWithEnum;

    case Pending = 'pending';
    case Active = 'active';
    case Inactive = 'inactive';
}

使用特质后,您可以调用以下方法

  • names()
StatusEnum::names()

返回

array:3 [
  0 => "Pending"
  1 => "Active"
  2 => "Inactive"
]
  • values()
StatusEnum::values()

返回

array:3 [
  0 => "pending"
  1 => "active"
  2 => "inactive"
]
  • array()
StatusEnum::array()

返回

array:3 [
  "pending" => "Pending"
  "active" => "Active"
  "inactive" => "Inactive"
]
  • find($needle)
StatusEnum::find('Active') // Find by name
StatusEnum::find('active') // Find by value

返回

App\Enums\StatusEnum {
  name: "Active"
  value: "active"
}