Monday, May 04, 2015

[Symfony] Controller

The controller - AppBundle:Random:index is the logical name of the controller, and it maps to the indexAction method of a PHP class called AppBundle\Controller\RandomController.

The Request as a Controller Argument

What if you need to read query parameters, grab a request header or get access to an uploaded file? All of that information is stored in Symfony's Request object. To get it in your controller, just add it as an argument and type-hint it with the Request class:

use Symfony\Component\HttpFoundation\Request;

public function indexAction($firstName, $lastName, Request $request)
{
$page = $request->query->get('page', 1); // from _GET
$data = $request->request->get('field1');// from _POST
...


The Base Controller Class

For convenience, Symfony comes with an optional base Controller class. If you extend it, you'll get access to a number of helper methods and all of your service objects via the container.

Add the use statement atop the Controller class and then modify the HelloController to extend it:


// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HelloController extends Controller
{
    // ...
}


When extending the base controller class, you can access any Symfony service via the get() method. Here are several common services you might need:

$templating = $this->get('templating');

$router = $this->get('router');

$mailer = $this->get('mailer');

What other services exist? To list all services, use the debug:container console command:

$ php app/console debug:container

Redirecting

If you want to redirect the user to another page, use the redirectToRoute() method.
 

public function indexAction()
{
    return $this->redirectToRoute('homepage');

    // redirectToRoute is equivalent to using redirect() and generateUrl() together:
    // return $this->redirect($this->generateUrl('homepage'), 301);
}



Reference:

symfony controller

No comments: