Symfony book 2 1

Page 51

1 public function indexAction($first_name, $last_name, $color, $foo = 2 'bar') 3 { 4 // ... }

• Not all routing parameters need to be arguments on your controller If, for example, the last_name weren't important for your controller, you could omit it entirely: Listing 5-10

1 public function indexAction($first_name, $color) 2 { 3 // ... 4 }

Every route also has a special _route parameter, which is equal to the name of the route that was matched (e.g. hello). Though not usually useful, this is equally available as a controller argument.

The Request as a Controller Argument For convenience, you can also have Symfony pass you the Request object as an argument to your controller. This is especially convenient when you're working with forms, for example: Listing 5-11

1 2 3 4 5 6 7 8 9

use Symfony\Component\HttpFoundation\Request; public function updateAction(Request $request) { $form = $this->createForm(...); $form->bind($request); // ... }

The Base Controller Class For convenience, Symfony2 comes with a base Controller class that assists with some of the most common controller tasks and gives your controller class access to any resource it might need. By extending this Controller class, you can take advantage of several helper methods. Add the use statement atop the Controller class and then modify the HelloController to extend it: Listing 5-12

1 2 3 4 5 6 7

// src/Acme/HelloBundle/Controller/HelloController.php namespace Acme\HelloBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class HelloController extends Controller

PDF brought to you by generated on February 4, 2013

Chapter 5: Controller | 51


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