Можно ли таким образом записать оператор where на шаблон репозитория в php? - PullRequest
0 голосов
/ 03 мая 2020

hi Может ли этот код быть рефакторингом?

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 таким образом, чтобы его не нужно было повторять?

Ответы [ 2 ]

0 голосов
/ 03 мая 2020

Вы можете выделить общую часть кода в приватный метод, а затем расширить базу с дополнительными функциями для каждого сценария ...

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).

0 голосов
/ 03 мая 2020
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')
    ];
}

Обработка обоих запросов в одной функции. Код более аккуратный и чистый, легко читаемый и понятный. Функция стрелки повышает читаемость над массивами.

...