Symfony2:放置业务逻辑的最佳位置 [英] Symfony2: Best place to put business logic

查看:23
本文介绍了Symfony2:放置业务逻辑的最佳位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到一个好的做法是实体轻,只有 getter 和 setter.但是我有一些带有逻辑的自定义方法,例如.

公共函数calculatePrice(){/*这里我要做很多数学运算包括访问其他存储库以获取来自其他实体的特定数据(税收、佣金等)*/}

在哪里放置这种更复杂的方法":

//在控制器中$product->calculatePrice()//在树枝模板中{{ product.calculatePrice }}

解决方案

我喜欢将与实体相关的业务逻辑放在一个 Service 类中.IMO,实体存储库应该只负责查询实体组的多个项目的数据库,或者非常具体的findBy"方法(例如:获取属于 UserMessages> 其中 isRead = 0).

通常,您会发现自己使用多个服务类来处理特定的业务逻辑块 - 将所有这些都保存在服务层中而不是将其硬塞到存储库中会更容易(也更干净).

将服务用于业务逻辑将导致代码更加模块化.如果您的 Product 实体和存储库不包含任何业务逻辑(通常每个应用都非常具体),您可以更轻松地在其他项目中重用这些类,而无需进行大量清理.

I read that a good practice have entities light, only getters and setters. But I have custom methods with some logic, for example.

public function calculatePrice(){

  /*
 Here I have to do many math operations 
 including access to other repositories to get 
 specific data (taxes, comissions, ect) from others entities
*/


}

Where to put this kind "more complex methods" for do:

//in controller
$product->calculatePrice()  

//in twig templates
{{ product.calculatePrice }}

解决方案

I like to put business logic related to entities within a Service class. IMO, an entity repository should only be responsible for querying the DB for multiple items of an entity group, or very specific 'findBy' methods (ex: fetch all Messages belonging to User where isRead = 0).

Often times, you'll find yourself using multiple service classes to handle specific blocks of business logic - it's easier (and cleaner) to keep all of this in the service layer instead of shoe-horning it into repositories.

Using services for business logic will result in more modular code. If your Product entity and repo don't contain any business logic (which is usually very specific per app), you can more easily reuse those classes in other projects without having to do as much cleanup.

这篇关于Symfony2:放置业务逻辑的最佳位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆