[英]Better way to validate the fields of an php object for empty values
i have a php object i called $product, it has several string properties. 我有一个名为$ product的php对象,它具有几个字符串属性。 Now i want to check the values of its fields to see if they are empty, but i am having to do this with many if statements like below, is there any smarter way?, i don't mind using a library 现在,我想检查其字段的值以查看它们是否为空,但是我不得不对许多类似以下的if语句执行此操作,有没有更聪明的方法?,我不介意使用库
private function validate(Product $product)
{
if (isEmpty($product->country)) {
throw New \Exception("country is empty");
} elseif (isEmpty($product->getCategory())) {
throw New \Exception("category is empty");
} elseif (isEmpty($product->getSubCategory())) {
throw New \Exception("subcategory is empty");
} elseif (isEmpty($product->getCoolingType())) {
throw New \Exception("category is empty");
} elseif (isEmpty($product->getPackagingType())) {
throw New \Exception("category is empty");
}
}
btw i am using symfony framwork 3.0 if that helps all the fields i am trying to validate are strings 顺便说一句,我正在使用symfony框架3.0,如果这有助于我尝试验证的所有字段都是字符串
You could loop them with the function names / error to print if returned value is empty as the key/value array. 如果返回值作为键/值数组为空,则可以使用函数名称/错误来循环打印它们。
Would look something like this: 看起来像这样:
<?php
private function validate(Product $product)
{
$functions = array("getCategory" => "category",
"getSubCategory" => "subcategory"
// as many function_name => error messages here as you want
);
foreach($functions as $function_name => $error) {
if(isEmpty($product->$function())) {
throw New \Exception("$error is empty");
}
}
}
Note that your first example, $product->country
doesn't fit this, so it would have to use a different case. 请注意,您的第一个示例$product->country
不适用于此示例,因此必须使用不同的大小写。
This answer explains what I'm doing with the if(isEmpty($product->$function())) {
line of code. 此答案说明了if(isEmpty($product->$function())) {
代码行的处理方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.