Where do code that adds/edit a model belong? Models or Controllers
I am using an MVC framework (Zend Framework) with ORM (Doctrine 2). On 1st look the answer seems to be models. But after some thought, I wonder if it should be in the controller. I am refering to functions like
static function addProduct($name, $desc, $quantity, $price) {
$product = new Product();
$product->name = $name;
$product->desc = $desc;
$product->quantity = $quantity;
$product->price = $price;
$em->persist($product);
$em->flush();
}
Such functions seem ok. But if I were to allow inline edits via AJAX. eg. just edit the product name, I think in my controller, I will use something like
$product->setName($name);
$em->flush();
But then since I need an Entity Manager $em
in my controller anyways, it will be like database code in my controllers already? Does it mean its I am doing it wrong? Or maybe I can just do something like
$product = new Product();
$product->setName($name);
$product->setDesc($desc);
$product->setQuantity($quantity);
$product->setPrice($price);
$em->开发者_如何学编程;persist($product);
$em->flush();
In my controller?
No , I don't think so , simply you are working in heavy Controller and light Models but this would make your code un reusable and you are going to write the same code many times in the same controller
and that is why i like heavy models and light controller
You're missing the service layer. The controller is just an agent to control objects (models) and variables running around. In my opinion the model classes just needs to be self representing models, and not aware of the entity manager.
I think you need to create a service layer in between. When saving/modifying a model, the controller calls a service object to do such. It's just saying "modify object $id with data $data" and the service layer performs this action. The result (success/failure) is passed back to the controller to act on this result.
精彩评论