php - 开关改进
问题描述
我有以下开关盒,但目前包含 10 个条件。
public function convertParameters(string $key, $value)
{
switch ($key) {
case "office":
case "name":
case "first_name":
case "last_name":
$value = ucfirst($value);
break;
case "email":
$value = strtolower($value);
break;
case "street":
case "city":
$value = ucwords($value);
break;
case "start":
case "end":
$value = \DateTime::createFromFormat("Y-m-d H:i:s", $value);
break;
}
return $value;
}
有谁知道我可以如何改进此功能以减少条件?(或其他改进)
解决方案
您的方法看起来不错,但如果您正在寻找替代方法,您可以使用从键映射到函数的数组。
$ops = [
"office" => "ucfirst",
"name" => "ucfirst",
"first_name" => "ucfirst",
"last_name" => "ucfirst",
"email" => "strtolower",
"street" => "ucwords",
"city" => "ucwords",
"start" => function($d) { return DateTime::createFromFormat("Y-m-d H:i:s", $d); },
"end" => function($d) { return DateTime::createFromFormat("Y-m-d H:i:s", $d); }
];
if (isset($ops[$key])) {
return $ops[$key]($value);
} else {
return $value;
}
推荐阅读
- spring - 存在 WebSecurityConfig 时出现 404
- html - 使用媒体查询,如何使其工作?
- javascript - 如何读取动态字符串作为对象引用
- firebase-dynamic-links - 对 Firebase 动态链接和 Wix 网站使用相同的域名
- python - python:如何计算结构张量的特征值和特征向量?
- python - 将 FFMPEG 添加到 macOS 路径以在 Python 中将 mp3 转换为 WAV 的问题
- json - Javascript - 从对象中获取返回 json
- javascript - 如何解决 slick.js 的“未捕获的类型错误:无法读取未定义的属性”
- java - Gson @AutoValue 和 Optional<> 不能一起工作,有解决方法吗?
- java - 如何在处理 DataIntegrityViolationException 时获取密钥的名称?