百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

enum

> 编程语言
开源

PHP 中的强类型枚举,支持自动完成和重构

851 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

PHP 中的强类型枚举,支持自动完成和重构

Enum

:warning: With the introduction of Enums in PHP 8.1, this package is now considered obsolete. For new projects, we recommend using native enums instead of this package. Learn more about native enums here: https://stitcher.io/blog/php-enums


This package offers strongly typed enums in PHP. In this package, enums are always objects, never constant values on their own. This allows for proper static analysis and refactoring in IDEs.

Here's how enums are created with this package:

use \Spatie\Enum\Enum;

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}

And this is how they are used:

public function setStatus(StatusEnum $status): void
{
    $this->status = $status;
}

// ...

$class->setStatus(StatusEnum::draft());

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/enum

Usage

This is how an enum can be defined.

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}

This is how they are used:

public function setStatus(StatusEnum $status)
{
    $this->status = $status;
}

// ...

$class->setStatus(StatusEnum::draft());
Autocompletion Refactoring

Creating an enum from a value

$status = StatusEnum::from('draft');

When an enum value doesn't exist, you'll get a BadMethodCallException. If you would prefer not catching an exception, you can use:

$status = StatusEnum::tryFrom('draft');

When an enum value doesn't exist in this case, $status will be null.

The only time you want to construct an enum from a value is when unserializing them from eg. a database.

If you want to get the value of an enum to store it, you can do this:

$status->value;

Note that value is a read-only property, it cannot be changed.

Enum values

By default, the enum value is its method name. You can however override it, for example if you want to store enums as integers in a database, instead of using their method name.

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
    protected static function values(): array
    {
        return [
            'draft' => 1,
            'published' => 2,
            'archived' => 3,
        ];
    }
}

An enum value doesn't have to be a string, as you can see in the example it can also be an int.

Note that you don't need to override all values. Rather, you only need to override the ones that you want to be different from the default.

If you have a logic that should be applied to all method names to get the value, like lowercase them, you can return a Closure.

/**
 * @method static self DRAFT()
 * @method static self PUBLISHED()
 * @method static self ARCHIVED()
 */
class StatusEnum extends Enum
{
    protected static function values(): Closure
    {
        return function(string $name): string|int {
            return mb_strtolower($name);
        };
    }
}

Enum labels

Enums can be given a label, you can do this by overriding the labels method.

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
    protected static function labels(): array
    {
        return [
            'draft' => 'my draft label',
        ];
    }
}

Note that you don't need to override all labels, the default label will be the enum's value.

If you have a logic that should be applied to all method names to get the label, like lowercase them, you can return a Closure as in the value example.

You can access an enum's label like so:

$status->label;

Note that label is a read-only property, it cannot be changed.

Comparing enums

Enums can be compared using the equals method:

$status->equals(StatusEnum::draft());

You can pass several enums to the equals method, it will return true if the current enum equals one of the given values.

$status->equals(StatusEnum::draft(), StatusEnum::archived());

Phpunit Assertions

This package provides an abstract class Spatie\Enum\Phpunit\EnumAssertions with some basic/common assertions if you have to test enums.

…

Faker Provider

Possibly you are using faker and want to generate random enums. Because doing so with default faker is a lot of copy'n'paste we've got you covered with a faker provider Spatie\Enum\Faker\FakerEnumProvider.

use Spatie\Enum\Faker\FakerEnumProvider;
use Faker\Generator as Faker;

/** @var Faker|FakerEnumProvider $faker */
$faker = new Faker();
$faker->addProvider(new FakerEnumProvider($faker));

$enum = $faker->randomEnum(StatusEnum::class);
$value = $faker->randomEnumValue(StatusEnum::class);
$label = $faker->randomEnumLabel(StatusEnum::class);

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

  • Brent Roose
  • All Contributors

License

The MIT License (MIT). Please see License File for more information.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPenumphp

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言