Symfony book 2 1

Page 52

8 { 9 10 11 12 13 }

public function indexAction($name) { return new Response('<html><body>Hello '.$name.'!</body></html>'); }

This doesn't actually change anything about how your controller works. In the next section, you'll learn about the helper methods that the base controller class makes available. These methods are just shortcuts to using core Symfony2 functionality that's available to you with or without the use of the base Controller class. A great way to see the core functionality in action is to look in the Controller1 class itself. Extending the base class is optional in Symfony; it contains useful shortcuts but nothing mandatory. You can also extend ContainerAware2. The service container object will then be accessible via the container property.

You can also define your Controllers as Services.

Common Controller Tasks Though a controller can do virtually anything, most controllers will perform the same basic tasks over and over again. These tasks, such as redirecting, forwarding, rendering templates and accessing core services, are very easy to manage in Symfony2.

Redirecting If you want to redirect the user to another page, use the redirect() method: Listing 5-13

1 public function indexAction() 2 { 3 return $this->redirect($this->generateUrl('homepage')); 4 }

The generateUrl() method is just a helper function that generates the URL for a given route. For more information, see the Routing chapter. By default, the redirect() method performs a 302 (temporary) redirect. To perform a 301 (permanent) redirect, modify the second argument: Listing 5-14

1 public function indexAction() 2 { 3 return $this->redirect($this->generateUrl('homepage'), 301); 4 }

1. http://api.symfony.com/2.1/Symfony/Bundle/FrameworkBundle/Controller/Controller.html 2. http://api.symfony.com/2.1/Symfony/Component/DependencyInjection/ContainerAware.html

PDF brought to you by generated on February 4, 2013

Chapter 5: Controller | 52


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