【发布时间】:2016-11-15 17:20:41
【问题描述】:
我是 Symfony 3 的新手,我想避免 我的控制器中的业务逻辑。 到目前为止我所做的是:
<?php
namespace RestBundle\Controller;
use RestBundle\Entity\Attribute;
use RestBundle\Entity\DistributorProduct;
use RestBundle\Entity\AttributeValue;
use RestBundle\Entity\ProductToImage;
use Symfony\Component\HttpFoundation\Request;
use RestBundle\Entity\Product;
use FOS\RestBundle\Controller\FOSRestController;
/**
* Product controller.
*
*/
class ProductController extends FOSRestController
{
/**
* Creates a new Product entity.
*
*/
public function createProductAction(Request $request)
{
// Doctrine Manager
$em = $this->getDoctrine()->getManager();
// todo: get the logged in distributor object
$distributor = $em->getRepository('RestBundle:Distributor')->find(1);
// Main Product
$product = new Product();
$product->setEan($request->get('ean'));
$product->setAsin($request->get('asin'));
$em->persist($product);
// New Distributor Product
$distributorProduct = new DistributorProduct();
$distributorProduct->setDTitle($request->get('title'));
$distributorProduct->setDDescription($request->get('description'));
$distributorProduct->setDPrice($request->get('price'));
$distributorProduct->setDProductId($request->get('product_id'));
$distributorProduct->setDStock($request->get('stock'));
// Relate this distributorProduct to the distributor
$distributorProduct->setDistributor($distributor);
// Relate this distributorProduct to the product
$distributorProduct->setProduct($product);
$em->persist($distributorProduct);
// Save it
$em->flush();
$response = $em->getRepository('RestBundle:Product')->find($product->getUuid());
return array('product' => $response);
}
}
}
我知道这不是好的代码,因为所有的业务逻辑都在控制器中。
但是,我如何以及在哪里可以将此代码(将请求设置为模型、持久化并使用原则刷新等)放入服务或对其使用依赖注入?还是为此目的的服务不是正确的方式?
我知道这个页面和教程http://symfony.com/doc/current/best_practices/business-logic.html 但我不清楚将 CRUD 操作放在哪里。 一项服务是否可以保存具有所有相关实体的整个项目?并使用 Symfony\Component\HttpFoundation\Request;在服务中?那么将整个控制器代码放在我收到请求并将模型分配给服务的地方吗? 谢谢
【问题讨论】:
-
如果你使用某种表单来创建产品,那么使用 Symfony 表单会自动将表单数据映射到你的实体数据:symfony.com/doc/current/book/forms.html
-
放入单独的服务并在其中注入实体管理器
-
不,我只使用 API,所以没有视图。只接收 POST 数据,分配给不同的实体,保存,响应保存的产品。
-
好的,但该服务的最佳实践是什么?一项服务是否可以保存具有所有相关实体的整个项目?并使用 Symfony\Component\HttpFoundation\Request;在服务中?那么把我收到请求并分配给模型的整个控制器代码放入服务中?
标签: php dependency-injection doctrine-orm symfony