【问题标题】:Can the where statement be written in such a way on repository pattern in php?php中的存储库模式可以这样写where语句吗?
【发布时间】:2020-05-03 07:15:25
【问题描述】:

你好,这段代码可以重构吗?

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语句可以写成不需要重复的吗?

【问题讨论】:

    标签: php laravel repository-pattern


    【解决方案1】:

    您可以将代码的公共部分分解为私有方法,然后使用每个场景的额外功能扩展基础...

    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 代码)。

    【讨论】:

      【解决方案2】:
      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')
          ];
      }
      

      在一个函数中处理这两个请求。代码更加整洁干净,易于阅读和理解。箭头函数增加了数组的可读性。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2012-12-30
      • 2017-05-07
      • 1970-01-01
      • 2016-04-19
      相关资源
      最近更新 更多