控制器是否適合這種行爲?
是的。
這種行爲在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,當然,創建相應的模板。
這是行不通的?你沒有序列化/ json_encode教條實體... – 2013-02-11 16:02:47
其實我做過。查看最後一個代碼塊'{{data | json_encode |原文}} – 2014-01-29 08:32:11