Is the controller the right place for this kind of behavior?
Yes.
What does this kind of behavior look like in Symfony2?
What are the best practices (within Symfony) for solving this kind of problem?
In symfony it looks pretty much alike, but there are couple of nuances.
I want to suggest my approach for this stuff. Let's start from routing:
# src/Scope/YourBundle/Resources/config/routing.yml
ScopeYourBundle_people_list:
pattern: /people
defaults: { _controller: ScopeYourBundle:People:list, _format: json }
The _format
parameter is not required but you will see later why it's important.
Now let's take a look at controller
<?php
// src/Scope/YourBundle/Controller/PeopleController.php
namespace OverseerMainBundleController;
use SymfonyBundleFrameworkBundleControllerController;
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 renders data in the format which is set in the routing config. In our case it's the json format.
Here is example of possible template:
{# app/Resourses/views/base.json.twig #}
{{ data | json_encode | raw }}
The advantage of this approach (I mean using _format) is that it if you decide to switch from json to, for example, xml than no problem - just replace _format in routing config and, of course, create corresponding template.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…