Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Best place to put business logic

Tags:

symfony

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 }}
like image 954
smoreno Avatar asked Dec 21 '22 19:12

smoreno


1 Answers

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.

like image 84
Steven Mercatante Avatar answered Dec 26 '22 16:12

Steven Mercatante