doctrine2 - Symfony2 Architecture: How to separate data access from business logic? -
i building symfony2 application doctrine. have doctrine entity objects in "entity" folder , have rest controllers in controller folder. want add together reusable business logic.
i'll seek give abstract/simple example: imagine have product consists of parts. parts have price. want cost of product.
so have entity called product has arraycollection (doctrine manytoone / onetomany) of producthaspart entities reference part. cost of product sum of prices of associated parts multiplied amount how need part in product stored in relationship (producthaspart)
intuitively code function "getprice" product entity, feels wrong:
this mix info access , business logic my entities quite huge because business logic functions can quite complex this create testing business logic complicated.so set function "calculatecosts()" ?
i have found far 2 theoretical approaches: services , models. read quite symfony2 has no constraints on this, haven't found code examples yet.
you can create service named calculation. cost calculation. can pass not product entity calculatedinterface. code can reused other entity implemented calculatedinterface
example
service.yml:
calculation: class: %calculation.class% service:
class calculation { /** * @param $entity */ public function calculate($entity) { $entity->settotal($entity->getvalue1() + $entity->getvalue2()); } ... in controller
$this->get('calculation')->calculate($entity); $entitymanager->persist($entity); $entitymanager->flush(); symfony2 doctrine2
No comments:
Post a Comment