定制 spatie/enum 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

spatie/enum

Composer 安装命令:

composer require spatie/enum

包简介

PHP Enums

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

⚠️ 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.

use Spatie\Enum\Phpunit\EnumAssertions;

EnumAssertions::assertIsEnum($post->status); // checks if actual extends Enum::class
EnumAssertions::assertIsEnumValue(StatusEnum::class, 'draft'); // checks if actual is a value of given enum
EnumAssertions::assertIsEnumLabel(StatusEnum::class, 'draft'); // checks if actual is a label of given enum
EnumAssertions::assertEqualsEnum(StatusEnum::draft(), 'draft'); // checks if actual (transformed to enum) equals expected
EnumAssertions::assertSameEnum(StatusEnum::draft(), $post->status); // checks if actual is same as expected
EnumAssertions::assertSameEnumValue(StatusEnum::draft(), 1); // checks if actual is same value as expected
EnumAssertions::assertSameEnumLabel(StatusEnum::draft(), 'draft'); // checks if actual is same label as expected

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 security@spatie.be 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

License

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

spatie/enum 适用场景与选型建议

spatie/enum 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 32.22M 次下载、GitHub Stars 达 847, 最近一次更新时间为 2019 年 02 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「enum」 「enumerable」 「spatie」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 spatie/enum 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 spatie/enum 我们能提供哪些服务?
定制开发 / 二次开发

基于 spatie/enum 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 32.22M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 850
  • 点击次数: 16
  • 依赖项目数: 78
  • 推荐数: 2

GitHub 信息

  • Stars: 847
  • Watchers: 8
  • Forks: 67
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-02-07