grachevko/enum

此包已被弃用且不再维护。作者建议使用premier/enum包。

PHP Enum实现

2.2 2022-02-03 17:42 UTC

This package is auto-updated.

Last update: 2022-02-03 17:43:55 UTC


README

Latest Stable Version Total Downloads Scrutinizer Code Quality Code Coverage Build Status SensioLabsInsight

安装

composer require premier/enum

使用方法

namespace Premier\Enum;

/**
 * @method static DriveWheel front()
 * @method static DriveWheel rear()
 * @method static DriveWheel allDrive()
 * @method static DriveWheel fromCode(string $code)
 * @method bool   isFront()
 * @method bool   isRear()
 * @method bool   isAllDrive()
 * @method string toCode()
 */
final class DriveWheel extends Enum
{
    private const FRONT = 1;
    private const REAR = 2;
    private const ALL_DRIVE = 3;

    protected static $code = [
        self::FRONT => 'FWD',
        self::REAR => 'RWD',
        self::ALL_DRIVE => 'AWD',
    ];
}

// New instance
$drive = DriveWheel::create(1);
// or
$drive = DriveWheel::front();
// or
$drive = DriveWheel::fromCode('FWD');
// or
$drive = DriveWheel::from('code', 'FWD');

// Array instances
DriveWheel::all(); // [DriveWheel::front(), DriveWheel::rear(), DriveWheel::allDrive()]
DriveWheel::all(['FWD', 'RWD'], $reverse = false, $property = 'code'); // [DriveWheel::front(), DriveWheel::rear()]
DriveWheel::all([1, 2], $reverse = true); // [DriveWheel::allDrive()]

// Methods
$drive->toId();    // 1
$drive->to('id');  // 1
(string) $drive;   // '1'

$drive->toName(); // 'front'

$drive->toCode();   // 'FWD'
$drive->to('code'); // 'FWD'

$drive->isFront(); // true
$drive->isRear();  // false

$drive->eq(DriveWheel::front()); // false
$drive->eq(DriveWheel::rear());  // false

设计

  • 所有常量必须是私有的
  • 所有常量必须是整数类型
  • 所有属性不能是公开的
  • 所有属性必须是静态的
  • 属性必须包含所有定义的常量的值

Doctrine

此库附带Type类,用于Doctrine,以便轻松配置每个Enum作为Doctrine Type。

Premier\Enum\Doctrine\EnumType::register(Premier\Enum\Gender::class, 'gender_enum', $property = 'id');

class Entity 
{
    /**
    * @var Gender
    * 
    * @ORM\Column(type="gender_enum") 
    */
    public $gender;
}