PHP code example of hyperf-ext / enum
1. Go to this page and download the library: Download hyperf-ext/enum library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hyperf-ext / enum example snippets
declare(strict_types=1);
namespace App\Enum;
use HyperfExt\Enum\Enum;
final class UserType extends Enum
{
const Administrator = 0;
const Moderator = 1;
const Subscriber = 2;
const SuperAdministrator = 3;
}
UserType::Administrator // 值为 `0`
// 标准的 PHP 实例化方式,将期望的枚举值作为参数进行传递
$enumInstance = new UserType(UserType::Administrator);
// 与使用构造函数一样,用值来实例化
$enumInstance = UserType::fromValue(UserType::Administrator);
// 使用枚举的键名作为参数来实例化
$enumInstance = UserType::fromKey('Administrator');
// 以键名作为方法名来静态调用,利用 __callStatic 魔术方法
$enumInstance = UserType::Administrator();
// 尝试使用给定的键名或值实例化一个枚举。如果无法实例化,则返回 `null`
$enumInstance = UserType::coerce($someValue);
$userType = UserType::fromValue(UserType::SuperAdministrator);
$userType->key; // SuperAdministrator
$userType->value; // 0
$userType->description; // Super Administrator
$userType = UserType::fromValue(UserType::SuperAdministrator);
(string) $userType // '0'
$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
$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
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); // 返回 true
canPerformAction($userType2); // 返回 false
final class UserPermissions extends FlaggedEnum
{
const ReadComments = 1 << 0;
const WriteComments = 1 << 1;
const EditComments = 1 << 2;
const DeleteComments = 1 << 3;
// 接下来是 `1 << 4`,并依此类推…
}
final class UserPermissions extends FlaggedEnum
{
const ReadComments = 1 << 0;
const WriteComments = 1 << 1;
const EditComments = 1 << 2;
const DeleteComments = 1 << 3;
// 位标志组合
const Member = self::ReadComments | self::WriteComments; // 读取和写入权限
const Moderator = self::Member | self::EditComments; // Member 的所有权限,附加编辑权限
const Admin = self::Moderator | self::DeleteComments; // Moderator 的所有权限,附加删除权限
}
// 标准的 PHP 实例化方式,将所需的枚举值作为值数组或枚举实例数组传递
$permissions = new UserPermissions([UserPermissions::ReadComments, UserPermissions::EditComments]);
$permissions = new UserPermissions([UserPermissions::ReadComments(), UserPermissions::EditComments()]);
// 静态 flags 方法,同样将所需的枚举值作为值数组或枚举实例数组传递
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::EditComments]);
$permissions = UserPermissions::flags([UserPermissions::ReadComments(), UserPermissions::EditComments()]);
UserPermissions::flags([])->value === UserPermissions::None; // True
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->flags([UserPermissions::EditComments, UserPermissions::DeleteComments]); // 当前位标志为:EditComments, DeleteComments
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlag(UserPermissions::EditComments); // 当前位标志为:ReadComments, EditComments
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlags([UserPermissions::EditComments, UserPermissions::WriteComments]); // 当前位标志为:ReadComments, EditComments, WriteComments
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->removeFlag(UserPermissions::ReadComments); // 当前位标志为:WriteComments.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments, UserPermissions::EditComments]);
$permissions->removeFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // 当前位标志为:EditComments
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->hasFlag(UserPermissions::ReadComments); // True
$permissions->hasFlag(UserPermissions::EditComments); // False
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->hasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // True
$permissions->hasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // False
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->notHasFlag(UserPermissions::EditComments); // True
$permissions->notHasFlag(UserPermissions::ReadComments); // False
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->notHasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // True
$permissions->notHasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // False
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->getFlags(); // [UserPermissions::ReadComments(), UserPermissions::WriteComments()];
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);
$permissions->hasMultipleFlags(); // True;
$permissions->removeFlag(UserPermissions::ReadComments)->hasMultipleFlags(); // False
UserPermissions::Member()->getBitmask(); // 11;
UserPermissions::Moderator()->getBitmask(); // 111;
UserPermissions::Admin()->getBitmask(); // 1111;
UserPermissions::DeleteComments()->getBitmask(); // 1000;
use HyperfExt\Enum\Traits\CastsEnums;
use HyperfTest\Enum\Enums\UserType;
use Hyperf\Database\Model\Model;
class Example extends Model
{
use CastsEnums;
protected $casts = [
'random_flag' => 'boolean', // 标准的 hyperf 类型转换示例
'user_type' => UserType::class, // 枚举类型转换示例
];
}
$example = Example::first();
$example->user_type // UserType 实例
$example = Example::first();
// 设置使用枚举值
$example->user_type = UserType::Moderator;
// 设置使用枚举实例
$example->user_type = UserType::Moderator();
final class UserType extends Enum
{
const Administrator = 0;
const Moderator = 1;
public static function parseDatabase($value)
{
return (int) $value;
}
}
use App\Enum\UserType;
use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->timestamps();
$table->string('type')
->default(UserType::Moderator);
});
}
}
use App\Enum\UserType;
use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->timestamps();
$table->enum('type', UserType::getValues())
->default(UserType::Member);
});
}
}
use HyperfExt\Enum\Rules\EnumValue;
/**
* @Inject
* @var \Hyperf\Validation\ValidatorFactory
*/
protected $validatorFactory;
public function store(Request $request)
{
$validator = $this->validatorFactory->make($request->post(), [
'user_type' => ['
new EnumValue(UserType::class, false) // 关闭严格模式类型检查
use HyperfExt\Enum\Rules\EnumKey;
/**
* @Inject
* @var \Hyperf\Validation\ValidatorFactory
*/
protected $validatorFactory;
public function store(Request $request)
{
$validator = $this->validatorFactory->make($request->post(), [
'user_type' => ['
use HyperfExt\Enum\Rules\Enum;
/**
* @Inject
* @var \Hyperf\Validation\ValidatorFactory
*/
protected $validatorFactory;
public function store(Request $request)
{
$validator = $this->validatorFactory->make($request->post(), [
'user_type' => ['
'user_type' => ''
// storage/languages/en/enum.php
use App\Enum\UserType;
return [
// …
UserType::class => [
UserType::Administrator => 'Administrator',
UserType::SuperAdministrator => 'Super administrator',
],
];
// storage/languages/es/enum.php
use App\Enum\UserType;
return [
// …
UserType::class => [
UserType::Administrator => 'Administrador',
UserType::SuperAdministrator => 'Súper administrador',
],
];
use HyperfExt\Enum\Enum;
use HyperfExt\Enum\Contracts\LocalizedEnum;
final class UserType extends Enum implements LocalizedEnum
{
// ...
}
public static function getDescription($value): string
{
if ($value === self::SuperAdministrator) {
return 'Super admin';
}
return parent::getDescription($value);
}
Enum::macro('asFlippedArray', function() {
return array_flip(self::asArray());
});
UserType::getKeys(); // 返回 ['Administrator', 'Moderator', 'Subscriber', 'SuperAdministrator']
UserType::getValues(); // 返回 [0, 1, 2, 3]
UserType::getKey(1); // 返回 'Moderator'
UserType::getKey(UserType::Moderator); // 返回 'Moderator'
UserType::getValue('Moderator'); // 返回 1
UserType::hasKey('Moderator'); // 返回 'True'
UserType::hasValue(1); // 返回 'True'
// 可以禁用严格类型检查:
UserType::hasValue('1'); // 返回 'False'
UserType::hasValue('1', false); // 返回 'True'
UserType::getDescription(3); // 返回 'Super administrator'
UserType::getDescription(UserType::SuperAdministrator); // 返回 'Super administrator'
UserType::getRandomKey(); // 返回 'Administrator', 'Moderator', 'Subscriber' 或 'SuperAdministrator'
UserType::getRandomValue(); // 返回 0, 1, 2 或 3
UserType::asArray(); // 返回 ['Administrator' => 0, 'Moderator' => 1, 'Subscriber' => 2, 'SuperAdministrator' => 3]
UserType::asSelectArray(); // 返回 [0 => 'Administrator', 1 => 'Moderator', 2 => 'Subscriber', 3 => 'Super administrator']
var_dump(UserType::getInstances());
array(4) {
'Administrator' =>
class HyperfExt\Enum\Tests\Enums\UserType#415 (3) {
public $key =>
string(13) "Administrator"
public $value =>
int(0)
public $description =>
string(13) "Administrator"
}
'Moderator' =>
class HyperfExt\Enum\Tests\Enums\UserType#396 (3) {
public $key =>
string(9) "Moderator"
public $value =>
int(1)
public $description =>
string(9) "Moderator"
}
'Subscriber' =>
class HyperfExt\Enum\Tests\Enums\UserType#393 (3) {
public $key =>
string(10) "Subscriber"
public $value =>
int(2)
public $description =>
string(10) "Subscriber"
}
'SuperAdministrator' =>
class HyperfExt\Enum\Tests\Enums\UserType#102 (3) {
public $key =>
string(18) "SuperAdministrator"
public $value =>
int(3)
public $description =>
string(19) "Super administrator"
}
}
UserType::coerce(0); // 返回 UserType 的实例,该实例的值为 UserType::Administrator
UserType::coerce('Administrator'); // 返回 UserType 的实例,该实例的值为 UserType::Administrator
UserType::coerce(99); // 返回 null (无效的枚举值)
shell script
php bin/hyperf.php gen:enum UserType
shell script
php bin/hyperf.php enum:annotate
shell script
php bin/hyperf.php enum:annotate "App\Enum\UserType"
shell script
php bin/hyperf.php gen:enum UserPermissions --flagged
shell script
php bin/hyperf.php vendor:publish hyperf/translation
shell script
php bin/hyperf.php vendor:publish hyperf-ext/enum
shell script
php bin/hyperf.php gen:enum
shell script
php bin/hyperf.php enum:annotate
php
UserType::getRandomInstance(); // 返回随机值的 UserType 实例
php
UserType::fromValue(UserType::Administrator); // 返回 UserType 的实例,该实例的值为 UserType::Administrator