我想按照" symfony"的理念来减少控制器。也许我需要使用这些服务,或者有什么要标准的?
这是我的功能
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Entity\Users;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
...
/**
* @Route("/save", name="save")
* @Method({"GET"})
* @return Response
*/
public function saveAction()
{
//returns an array of users on this date
//array(
// "Kate" => 18,
// "John" => 24,
// "Albert" => 31,
//);
$users= $this->get("users")->users();
$em = $this->getDoctrine()->getManager();
$checkNow = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneBy(array("date" => $this->nowDate));
if(null === $checkNow) {
foreach($users as $name => $qty) {
$userDB = new User();
$userDB->setDate($this->nowDate);
$userDB->setQty($qty);
$userDB->setName($name);
$em->persist($userDB);
}
$em->flush();
}
return new Response("New users are added");
}
提前谢谢。
答案 0 :(得分:0)
Symfony只是一个框架并允许任何内容,但通常与数据库相关的内容在EntityRepository中完成。我通常将EntityRepositories保留用于复杂查询或数据库操作。
您可以通过服务来保持控制器的精益,如下所示:
示例控制器操作:
$users= $this->get("users")->users();
$userService = $this->get('user.service');
if (!$userService->hasUsersCreatedOn($this->nowDate) {
$userService->createMultiple($users);
}
return 'message';
示例用户服务:
public function createMultiple($users); // just loops through each and creates
public function create($name, $qty, $date) {
$user = new User();
$user->setDate($this->nowDate);
$user->setQty($qty);
$user->setName($name);
$this->entityManager->persist($user);
$this->entityManager->flush($user);
return $user;
}