在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):BenSampo/laravel-enum开源软件地址(OpenSource Url):https://github.com/BenSampo/laravel-enum开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):About Laravel EnumSimple, extensible and powerful enumeration implementation for Laravel.
Created by Ben Sampson Jump To
Documentation for older versionsYou are reading the documentation for
Please see the upgrade guide for information on how to upgrade to the latest version. GuideI wrote a blog post about using laravel-enum: https://sampo.co.uk/blog/using-enums-in-laravel InstallationRequirements
Via Composer composer require bensampo/laravel-enum Enum LibraryBrowse and download from a list of commonly used, community contributed enums. Basic UsageEnum DefinitionYou 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 InstantiationIt 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 php artisan enum:annotate You can annotate a single class by specifying the class name php artisan enum:annotate "App\Enums\UserType" Instance PropertiesOnce you have an enum instance, you can access the $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 CastingEnum instances can be cast to strings as they implement the $userType = UserType::fromValue(UserType::SuperAdministrator);
(string) $userType // '0' Instance EqualityYou can check the equality of an instance against any value by passing it to the $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 $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 HintingOne 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 EnumStandard 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:
Defining valuesWhen defining values you must use powers of 2, the easiest way to do this is by using the shift left 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 shortcutsYou can use the bitwise or 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 enumThere 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 enumsFlagged enums can contain no value at all. Every flagged enum has a pre-defined constant of UserPermissions::flags([])->value === UserPermissions::None; // True Flagged enum methodsIn 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): EnumSet 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): EnumAdd the given flag to the enum $permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlag(UserPermissions::EditComments); // Flags are now: ReadComments, EditComments. addFlags(array $flags): EnumAdd the given flags to the enum $permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlags([UserPermissions::EditComments, UserPermissions::WriteComments]); // Flags are now: ReadComments, EditComments, WriteComments. addAllFlags(): EnumAdd all flags to the enum $permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addAllFlags(); // Enum now has all flags removeFlag($flag): EnumRemove the given flag from the enum $permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->removeFlag(UserPermissions::ReadComments); // Flags are now: WriteComments. removeFlags(array $flags): EnumRemove 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(): EnumRemove all flags from the enum $permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->removeAllFlags(); hasFlag($flag): boolCheck 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): boolCheck 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): boolCheck 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): boolCheck 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(): boolCheck 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 |