好的,我们走了.我会尽力说教.
去做
构建一个API,根据URL参数搜索并返回数据库中的产品.
属性
首先,我们使用所有有效属性设置一个数组.
$props = [
'id',
'product_name',
'barcode',
'category_id',
'description',
'price'
];
参数
让我们将来自URL的所有参数存储在变量中:
$parameters = Input::all();
没有参数
如果传递了任何参数,我们可以选择包含其字段的所有产品并返回结果:
if (empty($parameters)) {
$products = Product::all();
return $products;
}
组织事物
让我们考虑一下我们有3个“类别”的参数:
>这决定了要选择的字段(可选).
>这决定了结果顺序(可选).
>这决定了搜索条款(可选).
识别字段
对于第一个类别,我们将使用fields参数来接收用逗号分隔每个字段的字符串.
$fieldsParam = $parameters['fields']; // Gets fields string.
$fieldsParamSplit = explode(',', $fieldsParam); // Split the fields string into array.
$fields = array_intersect($props, $fieldsParamSplit); // Gets only wanted fields.
命令
对于第二类,我们将使用接收特定字段(属性)名称的sortby参数.
$orderProp = null;
// Check if parameter "sortby" exists and if it is valid.
if (isset($parameters['sortby']) && in_array($parameters['sortby'], $props)) {
$orderProp = $parameters['sortby'];
}
有一些条款?
对于第三类,我们将使用所有参数(上面提到的参数除外)来构建搜索的where子句.
$clauses = [];
foreach ($props as $prop) {
// Check if the current property is present in parameters.
if (in_array($prop, array_keys($parameters))) {
// Each item represents a where clause.
$clauses[$prop] = $parameters[$prop];
}
}
建立集合
现在所有的参数都经过验证,我们可以构建产品集合并返回结果.
if ($orderProp) {
$products = Product::where($clauses)->orderBy($orderProp)->get($fields);
} else {
$products = Product::where($clauses)->get($fields);
}
return $products;