How to use controllers in symfony
what are controllers in symfony
what is use of controller in framework
we can send request and receive object in response
there are different $requests method for using in controllers.


$request->server->get(‘HTTP_HOST’); //server variables.
$request->getPathInfo(); //gets the URI.
$request->files->get(‘file’); //files posted in a form.

$request->query->get(‘foo’); //gets foo GET var.
$request->request->get(‘bar’); //gets POST var.

$request->cookies->get(‘PHPSESSID’); //cookies


How to make redirection possible in controllers


How to make forward request in controller

return $this->forward(‘Bundle:Controller:Action’);

how to render text from a controller
how to render text in symfony
how to render text in html in symfony

Rendering text from a controller:

return new Response(‘<html>…</html>’);

How to make redirect not found page in symfony
Redirect to 404 not found:

throw $this->createNotFoundException(message);
throw $this->createNotFoundException(“sorry , you have no access to it.”);

how to work with session in symfony
how to work with session using controller in symfony

Working with the session

You can manage session attributes with:

$session = $this->getRequest()->getSession();
we can shortcut as follows:


How to work with data in controller using session in symfony
$session->get(‘foo’,’default value’);

what are flash messages in symfony

Flash messages only last one request and they are stored in a FlashBag:

To iterate trough all flash messages in a template you can use:

{% for flashMessage in app.session.flashbag.get(‘notice’) %}
    <div class=”flash notice”>
        {{ flashMessage }}
{% endfor %}

Finally, here is an example of a controller class with Request and Response object in use.

namespace Symfony\YourBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
    public function indexAction()
        return $this->render(‘YourBundle:Default:index.html.twig’);

    public function contactAction(Request $request)
        //get request variables.
        //do something, call service, go to database, create form, send emails, etc…
        return $this->render(‘YourBundle:Default:feedback.html.twig’, array([template vars]));