声明:本文非博主原创,来自《Laravel 4 From Apprentice to Artisan》阅读的翻译理解。当然不是原译,可以保证90%的原创性。另外,由于是理解翻译,难免有错误,欢迎指正。欢迎转载,转载请注明出处,谢谢!单一职责原则引入了“SOLID”设计原则,这是由Robert“UncleBob”Martin开发的理论。它是良好应用程序设计的5条原则,包括:单一职责原则开闭原则里氏替换原则接口分离原则依赖倒置原则让我们通过代码示例深入研究这五个原则。这五项原则相互依存,一则兴则两则,一则则毁则一则。单一职责原则意味着一个类只有一个改变的理由。也就是说,一个类的职责范围是严谨而明确的。我们之前说过,无知是福。类只需要做好自己的工作,不需要去感知自己的依赖变化带来的影响。看下面的类:classOrderProcessor{publicfunction__construct(BillerInterface$biller){$this->biller=$biller;}publicfunctionprocess(Order$order){$recent=$this->getRecentOrderCount($order);if($recent>0){thrownewException('可能有重复订单。');$this->biller->bill($order->account->id,$order->amount);DB::table('orders')->insert(array('account'=>$order->account->id,'amount'=>$order->amount;'created_at'=>Carbon::now());}protectedfunctiongetRecentOrderCount(Order$order){$timestamp=Carbon::now()->subMinutes(5);返回DB::table('orders')->where('account',$order->account->id)->where('created_at','>=',$timestamps)->count();}}这个类的职责是什么?看名字就知道他是来处理订单的。但是从getRecentOrderCount方法可以看出,该方法需要检测数据库中的历史订单,判断订单是否重复。额外的验证意味着我们的订单处理程序必须修改验证规则以防数据存储发生变化。我们可以将此职责提取到一个单独的类OrderRepository中:classOrderRepository{publicfunctiongetRecentOrderCount(Account$account){$timestamp=Carbon::now()->subMinutes(5);返回DB::table('orders')->where('account',$account->id)->where('created_at','>=',$timestamp)->count();}publicfunctionlogOrder(Order$order){DB::table('orders')->insert(array('account'=>$order->account->id,'amount'=>$order->amount;'created_at'=>Carbon::now();));}}然后向OrderProcessor中注入一个类库,以减少其检测账户历史订单的责任:$this->orders=$orders;}publicfunctionprocess(Order$order){$recent=$this->orders->getRecentOrderCount($order->account);如果($最近>0){thrownewException('可能重复订单');$this->biller->bill($order->account->id,$order->amount);$this->orders->logOrder($order);}}现在我们抽象出订单数据收集的责任。当获取和记录订单的方法发生变化时,无需修改OrderProcessor类。现在的类库职责清晰单一,代码简洁,表现力强,可维护性也有很大提高。请记住,单一职责原则并不是说代码越少越好,而是说在写类的时候,类的职责必须非常明确,必须有一套可用的方法。这些方法必须在类中形成类的总体责任。有了这些根据既定职责编写的巧妙简洁的类,我们的代码就可以成为一个解耦的、可测试的、友好的可变架构。
