Controller

  • A controller is a PHP function you create that takes information from the HTTP request and constructs and returns an HTTP response (as a Symfony2 Response object).

  • The response could be an HTML page, an XML document, a serialized JSON array, an image, a redirect, a 404 error or anything else you can dream up.

  • The controller contains whatever arbitrary logic your application needs to render the content of a page.

  • The following controller would render a page that simply prints Hello world!:

use Symfony\Component\HttpFoundation\Response;
public function helloAction()
{
return new Response('Hello world!');
}
Here are a few common examples:
  • Controller A prepares a Response object representing the content for the homepage of the site.

  • Controller B reads the slug parameter from the request to load a blog entry from the database and create a Response object displaying that blog. If the slug can't be found in the database, it creates and returns a Response object with a 404 status code.

  • Controller C handles the form submission of a contact form. It reads the form information from the request, saves the contact information to the database and emails the contact information to the webmaster. Finally, it creates a Response object that redirects the client's browser to the contact form "thank you" page.

  • A Simple Controller
    While a controller can be any PHP callable (a function, method on an object, or a Closure), in Symfony2, a controller is usually a single method inside a controller object. Controllers are also called actions.
    // src/Application/HelloBundle/Controller/HelloController.php
    namespace Application\HelloBundle\Controller;
    use Symfony\Component\HttpFoundation\Response;
    class HelloController
    {
    public function indexAction($name)
    {
    return new Response('<html><body>Hello '.$name.'!</body></html>');
    }
    }