2012-02-05 43 views
10

我剛開始使用Symfony2,我試圖弄清楚正確的方法是從控制器回顯JSON(例如,People)用於ExtJS 4網格。Symfony2:從控制器中迴應JSON以用於ExtJS 4網格

我在做用香草MVC方法的一切,我的控制器將有方法稱爲像getList會調用People模型getList方法,把這些結果,並做這樣的事情:

<?php 
class PeopleController extends controller { 
    public function getList() { 
     $model = new People(); 
     $data = $model->getList(); 
     echo json_encode(array(
      'success' => true, 
      'root' => 'people', 
      'rows' => $data['rows'], 
      'count' => $data['count'] 
     )); 
    } 
} 
?> 
  • 這種行爲在Symfony2中看起來像什麼?
  • 控制器是否適合這種行爲?
  • 解決這類問題的最佳實踐(在Symfony中)是什麼?

回答

12

控制器是否適合這種行爲?

是的。

這種行爲在Symfony2中看起來像什麼?

解決這類問題的最佳實踐(在Symfony中)是什麼?

在symfony中它看起來非常相似,但有一些細微之處。

我想爲這個東西建議我的方法。讓我們從路由開始:不需要

# src/Scope/YourBundle/Resources/config/routing.yml 

ScopeYourBundle_people_list: 
    pattern: /people 
    defaults: { _controller: ScopeYourBundle:People:list, _format: json } 

_format參數,但你會看到後來它爲什麼重要。

現在讓我們來看看控制器

<?php 
// src/Scope/YourBundle/Controller/PeopleController.php 
namespace Overseer\MainBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class PeopleController extends Controller 
{ 
    public function listAction() 
    { 
    $request = $this->getRequest(); 

    // if ajax only is going to be used uncomment next lines 
    //if (!$request->isXmlHttpRequest()) 
     //throw $this->createNotFoundException('The page is not found'); 

    $repository = $this->getDoctrine() 
      ->getRepository('ScopeYourBundle:People'); 

    // now you have to retrieve data from people repository. 
    // If the following code looks unfamiliar read http://symfony.com/doc/current/book/doctrine.html 
    $items = $repository->findAll(); 
    // or you can use something more sophisticated: 
    $items = $repository->findPage($request->query->get('page'), $request->query->get('limit')); 
    // the line above would work provided you have created "findPage" function in your repository 

    // yes, here we are retrieving "_format" from routing. In our case it's json 
    $format = $request->getRequestFormat(); 

    return $this->render('::base.'.$format.'.twig', array('data' => array(
     'success' => true, 
     'rows' => $items, 
     // and so on 
    ))); 
    } 
    // ... 
}  

控制器渲染其中在路由配置設置格式的數據。在我們的例子中,它是json格式。

這裏例如可能的模板:

{# app/Resourses/views/base.json.twig #} 
{{ data | json_encode | raw }} 

這種做法(我的意思是使用_format)的優點是,如果你決定切換從JSON,例如,XML不是沒有問題 - 只是替換路由配置中的_format,當然,創建相應的模板。

+1

這是行不通的?你沒有序列化/ json_encode教條實體... – 2013-02-11 16:02:47

+0

其實我做過。查看最後一個代碼塊'{{data | json_encode |原文}} – 2014-01-29 08:32:11

8

我會避免使用模板來呈現數據,因爲轉義數據等職責是在模板中。相反,我使用PHP中的內置json_encode函數,正如您所建議的那樣。

設置如前面的回答表明在routing.yml中所述控制器的路由:

ScopeYourBundle_people_list: 
pattern: /people 
defaults: { _controller: ScopeYourBundle:People:list, _format: json } 

唯一附加步驟是迫使編碼在響應中。

<?php 
class PeopleController extends controller { 
    public function listAction() { 
     $model = new People(); 
     $data = $model->getList(); 
     $data = array(
      'success' => true, 
      'root' => 'people', 
      'rows' => $data['rows'], 
      'count' => $data['count'] 
     ); 
     $response = new \Symfony\Component\HttpFoundation\Response(json_encode($data)); 
     $response->headers->set('Content-Type', 'application/json'); 
     return $response; 
    } 
} 
?> 
+2

只是一個小小的提示,如果路由正確指定了'_format'選項,'Content-Type'頭由Symfony2自動設置,因爲它可以在'Response'類[here] ://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Response.php#L166)。因爲在這個例子中,格式是'json',所以具有值'application/json'的'Content-Type'頭部將被附加到響應中。 – Matt 2012-02-05 16:37:44

0

簡單。使用FOSRestBundle並僅從控制器返回People對象。

-2

使用

return JsonResponse($data, StatusCode, Headers); 
1

而是建立自己的響應,你也可以使用的內置JsonResponse

你定義像其他的答案路線建議:

ScopeYourBundle_people_list: 
pattern: /people 
defaults: { _controller: ScopeYourBundle:People:list, _format: json } 

並使用新的響應類型:

<?php 
class PeopleController extends controller { 
    public function listAction() { 
     $model = new People(); 
     $data = $model->getList(); 
     $data = array(
      'success' => true, 
      'root' => 'people', 
      'rows' => $data['rows'], 
      'count' => $data['count'] 
     ); 
     return new \Symfony\Component\HttpFoundation\JsonResponse($data); 
    } 
} 

欲瞭解更多信息,請參閱apidoc(2.6版本)。