jomisacu / enumerations
处理 PHP 中枚举的简单方法
v1.0.2
2022-08-10 00:29 UTC
Requires
- php: ^7.1|^8.0
README
一个用于处理枚举的简单类
为什么?
在某些情况下,我们不得不处理一组静态值,枚举可以帮助我们以安全的方式处理这些值。您可以在代码中使用对象而不是直接编写原始值,这样可以防止拼写错误和行为错误。这不仅仅是将值包装成常量,您还可以使用TypeHint来避免在方法和构造函数中发生错误的调用。
用例
静态值:状态、数据库枚举和选项
如果您有一个快递系统,您可以使用枚举来处理包裹状态:已发送、在途中、已收到。示例
<?php final class PakageState extends Jomisacu\Enumerations\Enumeration { public const SENT = 'sent'; public const IN_WAY = 'in-way'; public const RECEIVED = 'received'; } // retrieving from raw values $state = PackageState::fromValue($valueFromRequest); // throws an exception if invalid value // TypeHint class Package { private PackageState $state; public function changePackageState(PackageState $state) { $this->state = $state; } public function getPackageState() { return $this->state; } } // printing the value $package = new Package; $state = PackageState::fromValue($valueFromRequest); // throws an exception if invalid value $package->changePackageState($state); echo $package->getPackageState(); // prints sent, in-way or received
现在,您可以以安全的方式处理这些值。
外部值
在某些情况下,我们需要处理可能因外部原因而变化的值。想象一下一所提供多个学院专业的大学,并且按照惯例,它们决定使用三个字符代码。随着时间的推移,专业会增加,科目会改变等等。因此,他们决定添加前缀来扩展代码的大小,同时保持所有代码的大小相同。例如:软件工程师可能有代码 'XYZ',但在更改后可能变为 '0XYZ'。
之前的更改引入了以下问题
- 由于代码中的原始值没有意义,逻辑被破坏
- 由于没有与真实值匹配,数据库中的值现在已损坏
- 没有安全的方法来替换生产系统中的值,我们需要通过某种方式捕获错误
解决方案是枚举。请看下面的示例...
class Career extends Jomisacu\Enumerations\Enumeration { // WTF??? What is this? // using our own value we drop the dependency with external sources // but below we will see how to deal with these values // the values in the database are the values that we decided in the class constants public const SOFTWARE_ENGINEER = "a372d961-22d9-4cc4-a9ee-4cb47a15b26d"; public const ARCHITECT = "6d8165dc-621d-4279-bc71-4e4f4782d972"; // we always can get the current code // if external code changes we only need to update the code here // the values in the database are the values that we decided in the class constants public function getCode() { $codes = [ self::SOFTWARE_ENGINEER => '0XYZ', self::ARCHITECT => '0YYK', ]; return $codes[(string) $this->getValue()]; } // now, we can store a reference to the previous code, so we can interop with old formats public function getOldCode() { $codes = [ self::SOFTWARE_ENGINEER => 'XYZ', self::ARCHITECT => 'YYK', ]; return $codes[(string) $this->getValue()]; } }
享受它!