madison-solutions / enum
此包已被弃用且不再维护。没有建议替代包。
一个在PHP中定义类似Java或Swift Enum类型的系统
v2.0.0
2019-05-30 17:25 UTC
Requires
- php: ^7.1
Requires (Dev)
- phpunit/phpunit: ^7.4
README
在PHP中定义类似Java或Swift Enum类型的系统。
示例用法
通过创建一个扩展自\MadisonSolutions\Enum的类来定义枚举,然后使用definitions()
方法定义可能的枚举成员。
你可以在类中定义任何其他你喜欢的函数 - 在下面的示例中,有一个额外的charge()
方法用于计算运费。
请注意,构造函数是私有的 - 不能直接创建枚举类的实例。
class ShippingMethod extends \MadisonSolutions\Enum\Enum
{
public static function definitions() : array
{
return [
'collection' => [
'label' => 'Collection',
'description' => 'Collect in person from our store.',
'fixed_charge' => 0,
'charge_per_kg' => 0,
],
'van' => [
'label' => 'Local van delivery',
'description' => 'Local delivery by our own vans.',
'fixed_charge' => 10,
'charge_per_kg' => 0,
],
'courier' => [
'label' => 'Nationwide delivery',
'description' => 'Nationwide delivery by courier service.',
'fixed_charge' => 5,
'charge_per_kg' => 3,
],
];
}
public function charge($weight) {
return $this->fixed_charge + $weight * $this->charge_per_kg;
}
}
遍历成员
foreach (ShippingMethods::members() as $method) {
echo $method->label . ': ' . $method->charge($weight) . "\n";
}
获取成员的子集
$freeMethods = ShippingMethods::subset(function ($method) {
return $method->fixed_charge === 0 && $method->charge_per_kg === 0;
});
访问实例
你不应该直接创建任何枚举类的实例 - 而应使用类上的静态方法。
$van = ShippingMethods::van();
// or
$van = ShippingMethod::named('van');
从不受信任的输入创建实例
$method = ShippingMethod::maybeNamed($_POST['shipping-method']);
if (! $method) {
die("No such shipping method {$_POST['shipping-method']}");
}
比较实例
if ($method == ShippingMethods::collection()) {
echo "You are collecting in person.";
}
// or
if ($method->name == 'collection') {
echo "You are collecting in person.";
}
// or
switch ($method) {
case ShippingMethods::collection():
echo "You are collecting in person.";
break;
}
从/存储到数据库
// store
$stringValue = ShippingMethods::nameOf($method);
// save $stringValue in database
// load
$method = ShippingMethod::maybeNamed($stringValue);
或者可以使用serialize和unserialize方法,但是如果序列化的成员已不存在(例如,定义在保存数据与恢复数据之间发生了变化),unserialize将抛出UnexpectedValueException异常。
类型提示
function validateShippingMethod($order, ShippingMethod $method) {
if ($method === ShippingMethods::van()) {
if (! $order->address->isLocal()) {
die("Van delivery is only available for local addresses");
}
}
}