cruxinator / php-bitmask
PHP 位掩码实现
0.2.0
2023-09-16 06:46 UTC
Requires
- php: >=7.1 | >=8.0
- myclabs/php-enum: ^1.7
Requires (Dev)
- phpunit/phpunit: ^9.5
README
为什么?
首先,最主要的是,myclabs/php-enum
受限制且不能组合(Enum::FOO() | Enum::BAR() 也不太好用)。
使用位掩码而不是整数有以下优点
- 你可以进行类型提示:
function setAction(Bitmask $action) {
; - 你可以为位掩码添加方法(例如
format
,parse
等); - 你可以扩展位掩码以添加新值(使你的枚举
final
以防止它); - 你可以获取所有可能值的列表(见下文);
- 位掩码可以在单个值中包含许多枚举。
这个位掩码类不是为了取代枚举,而是当有实际意义时才使用。
安装
composer require cruxinator/php-bitmask
声明
use Cruxinator\BitMask\BitMask ; class UserStatus extends BitMask { const Registered = 1; // BIT #1 of $flags has the value 1 const Active = 2; // BIT #2 of $flags has the value 2 const Member = 4; // BIT #3 of $flags has the value 4 const Admin = 8; // BIT #4 of $flags has the value 8 }
用法
$status = UserStatus::Registered(); // or with a dynamic key: $status = UserStatus::$key(); // or with a dynamic value: $status = new UserStatus($value); // values can then be checked if ($status->isActive()){ // ... } // individuals flags can later toggled ON $status->setActive(true); // or off $status->setActive(false);
如您所见,方法已自动实现,以提供对位掩码值的快速访问。
与使用类常量相比的一个优点是可以对位图值进行类型提示
function setStatus(UserStatus $action) { // ... }
文档
__construct()
构造函数检查值是否可以由枚举组合;__toString()
你可以echo $myValue
,它将显示位掩码值(以布尔数组格式显示);getValue()
返回位掩码的当前值getKey()
返回位掩码当前组合部分的键数组equals()
测试位掩码实例是否相等(如果枚举值相等则返回true
,否则返回false
);
静态方法
toArray()
返回所有可能值的数组(键为常量名称,值为常量值);keys()
返回枚举类中所有常量的名称(键);values()
返回所有枚举常量的枚举类实例(键为常量名称,值为枚举实例);isValid()
检查测试值是否在枚举集中有效;isValidKey()
检查测试键是否在枚举集中有效;search()
返回搜索值的键;
动态方法
class UserStatus extends BitMask { private const Registered = 1; private const Active = 2; } // Static method: $status = UserStatus::Registered(); $status = UserStatus::Active(); // instance methods $status->isRegistered(); $status->isActive(); $status->setRegistered($bool); $status->setActive($bool);
使用 __callStatic()
和 __call()
实现了静态方法辅助器。
如果你关心 IDE 自动完成,你可以自己实现静态方法
class UserStatus extends BitMask { private const Registered = 1; /** * @return UserStatus */ public static function Registered() { return new UserStatus(self::Registered); } /** * @return bool */ public function isRegistered(){ return $this->isFlagSet(self::Registered); } /** * @param bool $flag * @return self */ public function setRegistered(bool $flag){ return $this->setFlag(self::Registered, $flag); } }
或者你可以使用 phpdoc(例如,这得到了 PhpStorm 的支持)
/** * @method static UserStatus Registered() * @method bool isRegistered() * @method UserStatus setRegistered(bool) */ class UserStatus extends Bitmask { private const Registered = 1; }
相关项目
- [myclabs/php-enum] (https://github.com/myclabs/php-enum)