你好,这段代码可以重构吗?
public function all(array $attributes)
{
$rates = $this->model->query()->where([
['able_type', $attributes['type']],
['able_id', $attributes['type_id']]
])
->get(['rate']);
return [
'count' => $rates->count(),
'average' => $rates->avg('rate')
];
}
public function show($attributes)
{
$result = $this->model->query()->where([
['user_id', $attributes['user_id']],
['able_type', $attributes['type']],
['able_id', $attributes['type_id']]
])
->first();
return $result;
}
where语句可以写成不需要重复的方式吗?
你可以把代码中常见的部分分解成一个私有方法,然后在基础上为每个场景扩展额外的功能......。
private function getBase () {
return $this->model->query()->where([
['able_type', $attributes['type']],
['able_id', $attributes['type_id']]
]);
}
public function all(array $attributes)
{
$rates = $this->getBase()
->get(['rate']);
return [
'count' => $rates->count(),
'average' => $rates->avg('rate')
];
}
public function show($attributes)
{
$result = $this->getBase()
->where('user_id', $attributes['user_id'])
->first();
return $result;
}
(虽然我假设这能行得通, 因为我不会编写Laravel代码).
public function get(array $attributes)
{
$rates = $this->model
->where('able_type', $attributes['type'])
->where('able_id', $attributes['type_id']);
if(!empty($attributes['user_id']))
{
return $rates->where('user_id', $attributes['user_id'])
->first();
}
return [
'count' => $rates->count(),
'average' => $rates->avg('rate')
];
}
在一个函数中处理这两个请求。代码更整洁&干净,易于阅读&理解。箭头函数比数组增加了再可读性。