• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

BenSampo/laravel-enum: Simple, extensible and powerful enumeration implementatio ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

BenSampo/laravel-enum

开源软件地址(OpenSource Url):

https://github.com/BenSampo/laravel-enum

开源编程语言(OpenSource Language):

PHP 100.0%

开源软件介绍(OpenSource Introduction):

Laravel Enum

Build Status Packagist Stable Version Packagist downloads MIT Software License

About Laravel Enum

Simple, extensible and powerful enumeration implementation for Laravel.

  • Enum key value pairs as class constants
  • Full-featured suite of methods
  • Enum instantiation
  • Flagged/Bitwise enums
  • Type hinting
  • Attribute casting
  • Enum artisan generator
  • Validation rules for passing enum key or values as input parameters
  • Localization support
  • Extendable via Macros

Created by Ben Sampson

Jump To

Documentation for older versions

You are reading the documentation for 5.x.

Please see the upgrade guide for information on how to upgrade to the latest version.

Guide

I wrote a blog post about using laravel-enum: https://sampo.co.uk/blog/using-enums-in-laravel

Installation

Requirements

  • Laravel 9 or higher
  • PHP 8.0 or higher

Via Composer

composer require bensampo/laravel-enum

Enum Library

Browse and download from a list of commonly used, community contributed enums.

Enum library →

Basic Usage

Enum Definition

You can use the following Artisan command to generate a new enum class:

php artisan make:enum UserType

Now, you just need to add the possible values your enum can have as constants.

<?php

namespace App\Enums;

use BenSampo\Enum\Enum;

final class UserType extends Enum
{
    const Administrator = 0;
    const Moderator = 1;
    const Subscriber = 2;
    const SuperAdministrator = 3;
}

That's it! Note that because the enum values are defined as plain constants, you can simple access them like any other class constant.

UserType::Administrator // Has a value of 0

Instantiation

It can be useful to instantiate enums in order to pass them between functions with the benefit of type hinting.

Additionally, it's impossible to instantiate an enum with an invalid value, therefore you can be certain that the passed value is always valid.

For convenience, enums can be instantiated in multiple ways:

// Standard new PHP class, passing the desired enum value as a parameter
$enumInstance = new UserType(UserType::Administrator);

// Same as the constructor, instantiate by value
$enumInstance = UserType::fromValue(UserType::Administrator);

// Use an enum key instead of its value
$enumInstance = UserType::fromKey('Administrator');

// Statically calling the key name as a method, utilizing __callStatic magic
$enumInstance = UserType::Administrator();

// Attempt to instantiate a new Enum using the given key or value. Returns null if the Enum cannot be instantiated.
$enumInstance = UserType::coerce($someValue);

If you want your IDE to autocomplete the static instantiation helpers, you can generate PHPDoc annotations through an artisan command.

By default all Enums in app/Enums will be annotated (you can change the folder by passing a path to --folder)

php artisan enum:annotate

You can annotate a single class by specifying the class name

php artisan enum:annotate "App\Enums\UserType"

Instance Properties

Once you have an enum instance, you can access the key, value and description as properties.

$userType = UserType::fromValue(UserType::SuperAdministrator);

$userType->key; // SuperAdministrator
$userType->value; // 0
$userType->description; // Super Administrator

This is particularly useful if you're passing an enum instance to a blade view.

Instance Casting

Enum instances can be cast to strings as they implement the __toString() magic method.
This also means they can be echoed in blade views, for example.

$userType = UserType::fromValue(UserType::SuperAdministrator);

(string) $userType // '0'

Instance Equality

You can check the equality of an instance against any value by passing it to the is method. For convenience, there is also an isNot method which is the exact reverse of the is method.

$admin = UserType::fromValue(UserType::Administrator);

$admin->is(UserType::Administrator);   // true
$admin->is($admin);                    // true
$admin->is(UserType::Administrator()); // true

$admin->is(UserType::Moderator);       // false
$admin->is(UserType::Moderator());     // false
$admin->is('random-value');            // false

You can also check to see if the instance's value matches against an array of possible values using the in method, and use notIn to check if instance value is not in an array of values. Iterables can also be checked against.

$admin = UserType::fromValue(UserType::Administrator);

$admin->in([UserType::Moderator, UserType::Administrator]);     // true
$admin->in([UserType::Moderator(), UserType::Administrator()]); // true

$admin->in([UserType::Moderator, UserType::Subscriber]);        // false
$admin->in(['random-value']);                                   // false

$admin->notIn([UserType::Moderator, UserType::Administrator]);     // false
$admin->notIn([UserType::Moderator(), UserType::Administrator()]); // false

$admin->notIn([UserType::Moderator, UserType::Subscriber]);        // true
$admin->notIn(['random-value']);                                   // true

Type Hinting

One of the benefits of enum instances is that it enables you to use type hinting, as shown below.

function canPerformAction(UserType $userType)
{
    if ($userType->is(UserType::SuperAdministrator)) {
        return true;
    }

    return false;
}

$userType1 = UserType::fromValue(UserType::SuperAdministrator);
$userType2 = UserType::fromValue(UserType::Moderator);

canPerformAction($userType1); // Returns true
canPerformAction($userType2); // Returns false

Flagged/Bitwise Enum

Standard enums represent a single value at a time, but flagged or bitwise enums are capable of of representing multiple values simultaneously. This makes them perfect for when you want to express multiple selections of a limited set of options. A good example of this would be user permissions where there are a limited number of possible permissions but a user can have none, some or all of them.

You can create a flagged enum using the following artisan command:

php artisan make:enum UserPermissions --flagged

Defining values

When defining values you must use powers of 2, the easiest way to do this is by using the shift left << operator like so:

final class UserPermissions extends FlaggedEnum
{
    const ReadComments      = 1 << 0;
    const WriteComments     = 1 << 1;
    const EditComments      = 1 << 2;
    const DeleteComments    = 1 << 3;
    // The next one would be `1 << 4` and so on...
}

Defining shortcuts

You can use the bitwise or | to set a shortcut value which represents a given set of values.

final class UserPermissions extends FlaggedEnum
{
    const ReadComments      = 1 << 0;
    const WriteComments     = 1 << 1;
    const EditComments      = 1 << 2;
    const DeleteComments    = 1 << 3;

    // Shortcuts
    const Member = self::ReadComments | self::WriteComments; // Read and write.
    const Moderator = self::Member | self::EditComments; // All the permissions a Member has, plus Edit.
    const Admin = self::Moderator | self::DeleteComments; // All the permissions a Moderator has, plus Delete.
}

Instantiating a flagged enum

There are couple of ways to instantiate a flagged enum:

// Standard new PHP class, passing the desired enum values as an array of values or array of enum instances
$permissions = new UserPermissions([UserPermissions::ReadComments, UserPermissions::EditComments]);
$permissions = new UserPermissions([UserPermissions::ReadComments(), UserPermissions::EditComments()]);

// Static flags method, again passing the desired enum values as an array of values or array of enum instances
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::EditComments]);
$permissions = UserPermissions::flags([UserPermissions::ReadComments(), UserPermissions::EditComments()]);

Attribute casting works in the same way as single value enums.

Empty flagged enums

Flagged enums can contain no value at all. Every flagged enum has a pre-defined constant of None which is comparable to 0.

UserPermissions::flags([])->value === UserPermissions::None; // True

Flagged enum methods

In addition to the standard enum methods, there are a suite of helpful methods available on flagged enums.

Note: Anywhere where a static property is passed, you can also pass an enum instance.

setFlags(array $flags): Enum

Set the flags for the enum to the given array of flags.

$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->flags([UserPermissions::EditComments, UserPermissions::DeleteComments]); // Flags are now: EditComments, DeleteComments.

addFlag($flag): Enum

Add the given flag to the enum

$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlag(UserPermissions::EditComments); // Flags are now: ReadComments, EditComments.

addFlags(array $flags): Enum

Add the given flags to the enum

$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlags([UserPermissions::EditComments, UserPermissions::WriteComments]); // Flags are now: ReadComments, EditComments, WriteComments.

addAllFlags(): Enum

Add all flags to the enum

$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addAllFlags(); // Enum now has all flags

removeFlag($flag): Enum

Remove the given flag from the enum

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->removeFlag(UserPermissions::ReadComments); // Flags are now: WriteComments.

removeFlags(array $flags): Enum

Remove the given flags from the enum

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments, UserPermissions::EditComments]);
$permissions->removeFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // Flags are now: EditComments.

removeAllFlags(): Enum

Remove all flags from the enum

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->removeAllFlags();

hasFlag($flag): bool

Check if the enum has the specified flag.

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->hasFlag(UserPermissions::ReadComments); // True
$permissions->hasFlag(UserPermissions::EditComments); // False

hasFlags(array $flags): bool

Check if the enum has all of the specified flags.

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->hasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // True
$permissions->hasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // False

notHasFlag($flag): bool

Check if the enum does not have the specified flag.

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->notHasFlag(UserPermissions::EditComments); // True
$permissions->notHasFlag(UserPermissions::ReadComments); // False

notHasFlags(array $flags): bool

Check if the enum doesn't have any of the specified flags.

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->notHasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // True
$permissions->notHasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // False

getFlags(): Enum[]

Return the flags as an array of instances.

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->getFlags(); // [UserPermissions::ReadComments(), UserPermissions::WriteComments()];

hasMultipleFlags(): bool

Check if there are multiple flags set on the enum.

$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->hasMultipleFlags(); // True;
$permissions->removeFlag(UserPermissions::ReadComments)->hasMultipleFlags(); // False

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap