【问题标题】:Laravel and performing logic on a modelLaravel 并在模型上执行逻辑
【发布时间】:2015-02-03 14:43:13
【问题描述】:

我正在尝试在我的应用中采用 SOLID 原则。

假设我有这两个模型:

客户(字段=idnameaddress 等)有很多

控股(字段=idclient_idtickerholding_datevalue

在我的 ClientsController 中,我可能有这样的方法:

public function show($id)
{
 $client = Client::find($id);
 $client->setValuations();
 $valuations = $client->getValuations();    

 return View::make('clients.show')-with(compact('client', 'valuations'));
}

因此,在控制器中,我想为客户获取一段时间内的估值。我的客户端模型上的setValuations() 执行了一个相当复杂的查询,该查询汇总了客户端的持有量并将结果集合设置为客户端上的属性。

所以我的客户端模型可能有点像:

class Client extends \Eloquent {

 // All the usual model stuff

 protected $valuations;

 public function setValuations()
 {
  $this->valuations = DB::table('holdings')
        ->select('holdings.holding_date', DB::raw('SUM(holdings.value) AS sumofvalue') )
        ->where('holdings.client_id', $this->id)
        ->where('holdings.holding_date', DB::raw('LAST_DAY(holdings.holding_date)') )
        ->groupBy('holdings.holding_date')
        ->orderBy('holdings.holding_date', 'asc')
        ->get();
        return $this;
 }

 public function getValuations()
 {
  return $this->valuations;
 }
}

正如我们所看到的,在模型中放入相当多的废话(为了简洁起见,我已经对其进行了很多压缩!)。我应该认为使用存储库模式可能是最好的方法,但我不确定如何构建它。假设我有几个与客户相关的属性需要进行大量查询或处理以确定它们是什么(例如 returns客户货币交易 - 这需要应用例如,fx 转换为值的集合),如何构建这个的最佳方式以及逻辑应该放在哪里?

【问题讨论】:

    标签: php laravel laravel-4 solid-principles


    【解决方案1】:

    你完全正确。保持这样的逻辑会使模型膨胀并导致违反 SOLID 原则。我使用存储库模式将这种逻辑从我的模型中移出(谁不应该承担该责任,即单一责任原则)并进入专用类。

    我建议你看看像 Laravel.io 网站这样利用存储库模式的开源项目。看到他们的代码后,您应该能够自己应用该模式。这是一个链接https://github.com/LaravelIO/laravel.io

    我也强烈推荐https://www.laracasts.com。对 SOLID 原则和存储库模式进行了深入讨论,极大地提高了我对 Laravel 和编码最佳实践的理解。

    【讨论】:

    • 是的,存储库模式是我要去的方向。我认为对于更复杂的处理,我会进一步将此逻辑抽象为一个单独的类(例如,用于计算回报)。我是 laracasts 的狂热订阅者,所以一直在浏览相关视频。
    猜你喜欢
    • 2018-10-15
    • 2012-12-23
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多