brysem / phpenums
在PHP中简化枚举。
v1.0.5
2022-07-18 07:17 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ~2
- phpunit/phpunit: ~4.0 || ~5.0
This package is not auto-updated.
Last update: 2024-09-26 01:45:42 UTC
README
在PHP中简化枚举。为您提供易于使用的接口。
<?php // Assume that this model will now give us access to the property "status" // which has been set to an instance of the UserStatus enum class. $user = new Models\User([ 'status' => new UserStatus(UserStatus::ACTIVE) ]); echo("Hello, your account is currently ". $user->status ."."); // __toString() -> Hello, your account is currently Active. // Get all values. UserStatus::all(); // [1 => 'Pending', 2 => 'Active', 3 => 'Banned'] // Get all keys from the enum. UserStatus::keys(); // [1, 2, 3] $userStatus = new UserStatus(UserStatus::ACTIVE); $userStatus->values(); // [1 => 'Pending', 2 => 'Active', 3 => 'Banned'] // Cast to a string. (string) $user->status; // Active // Perform checks $user->status->is(UserStatus::ACTIVE); // true $user->status->is([UserStatus::ACTIVE, UserStatus::PENDING]); // true (checkes whether the status is active or pending.) $user->status->has(UserStatus::PENDING); // true $user->status->has(1337); // false // Set and get the value. $user->status->value(); // 2 $user->status->set(UserStatus::ACTIVE); // Active $user->status->get(UserStatus::ACTIVE); // Active // Safegaurding against invalid values try { $user->status->set(1337); $user->status->set('undefined'); } catch (UndefinedEnumValueException $e) { // } catch (InvalidArgumentException $e) { // }
安装
可以使用 Composer 安装PHP Enums。
$ composer require brysem/phpenums
{ "require": { "brysem/phpenums": "1.*" } }
<?php require 'vendor/autoload.php'; use Bryse\Enums\Enum; class UserStatus extends Enum { const PENDING = 1; const ACTIVE = 2; const BANNED = 3; /** * Returns all possible key value pairs for the enum. * * @return array */ public function values() { return [ self::PENDING => 'Pending', self::ACTIVE => 'Active', self::BANNED => 'Banned', ]; } }
Laravel 示例
<?php namespace App\Models; use App\Models\Enums\UserType; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { public function getTypeAttribute() { return new UserType($this->attributes['type']); } public function setTypeAttribute($value) { $this->attributes['type'] = (new UserType($value))->value(); } }
您现在可以轻松执行以下操作。
$user->status = UserType::ACTIVE;
特性
- 自动字符串转换。
- 有用的检查和比较。
- 易于在任何框架或纯PHP文件中使用。
- PSR-4 自动加载兼容结构。
- 使用PHPUnit进行单元测试。
贡献
感谢您考虑为PHP Enums做出贡献。任何帮助都将受到赞赏。请随时发送pull request。
许可
PHP Enums软件包是开源软件,根据MIT许可证许可。