Symfony book 2 1

Page 47

Chapter 5

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. See how simple this is by looking at a Symfony2 controller in action. The following controller would render a page that simply prints Hello world!: Listing 5-1

1 2 3 4 5 6

use Symfony\Component\HttpFoundation\Response; public function helloAction() { return new Response('Hello world!'); }

The goal of a controller is always the same: create and return a Response object. Along the way, it might read information from the request, load a database resource, send an email, or set information on the user's session. But in all cases, the controller will eventually return the Response object that will be delivered back to the client. There's no magic and no other requirements to worry about! 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.

PDF brought to you by generated on February 4, 2013

Chapter 5: Controller | 47


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.