2016-06-16 7 views
0

「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

をあなたがより良いではいくつかの例を経ますここに:http://www.inanzzz.com/index.php/posts/symfony – BentCoder

+0

BentCoderリンクありがとう – user3771955

答えて

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; 
} 
+0

mickadooあなたの助けをありがとう – user3771955

+0

@ user3771955いいえp汚れ(通常、人々はアップヴォート/有益な回答を受け入れる) – mickadoo

関連する問題