gpt4 book ai didi

php - Symfony2 : Echoing JSON From a Controller for Use in an ExtJS 4 Grid

转载 作者:可可西里 更新时间:2023-10-31 22:42:15 25 4
gpt4 key购买 nike

我刚刚开始使用 Symfony2,我正在尝试弄清楚从 Controller (例如,People)回显 JSON 以用于 ExtJS 4 网格的正确方法是什么.

当我使用 vanilla MVC 方法做所有事情时,我的 Controller 会有类似 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 中是什么样的?
  • Controller 是否适合这种行为?
  • 解决此类问题的最佳实践(在 Symfony 中)是什么?

最佳答案

Is the controller the right place for this kind of behavior?

是的。

What does this kind of behavior look like in Symfony2?

What are the best practices (within Symfony) for solving this kind of problem?

在 symfony 中它看起来很相似,但有一些细微差别。

我想提出我的处理方法。让我们从路由开始:

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

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

_format 参数不是必需的,但您稍后会看到为什么它很重要。

现在让我们来看看 Controller

<?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
)));
}
// ...
}

Controller 以路由配置中设置的格式呈现数据。在我们的例子中,它是 json 格式。

这是可能的模板示例:

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

这种方法(我的意思是使用 _format)的优点是,如果您决定从 json 切换到 xml 等,那么没问题 - 只需替换路由配置中的 _format,当然,还可以创建相应的模板。

关于php - Symfony2 : Echoing JSON From a Controller for Use in an ExtJS 4 Grid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com