21.10.2015 Views

1-33

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Symfony2 – Franz Jordán 2011<br />

// ...<br />

new Acme\HelloBundle\AcmeHelloBundle(),<br />

);<br />

// ...<br />

return $bundles;<br />

}<br />

Now that you have a bundle setup, you can begin building your application inside the bundle.<br />

Step 1: Create the Route<br />

By default, the routing configuration file in a Symfony2 application is located<br />

atapp/config/routing.yml. Like all configuration in Symfony2, you can also choose to use<br />

XML or PHP out of the box to configure routes.<br />

If you look at the main routing file, you'll see that Symfony already added an entry when you<br />

generated the AcmeHelloBundle:<br />

YAML<br />

# app/config/routing.yml<br />

AcmeHelloBundle:<br />

resource: "@AcmeHelloBundle/Resources/config/routing.yml"<br />

prefix: /<br />

This entry is pretty basic: it tells Symfony to load routing configuration from<br />

theResources/config/routing.yml file that lives inside the AcmeHelloBundle. This<br />

means that you place routing configuration directly in app/config/routing.yml or organize<br />

your routes throughout your application, and import them from here.<br />

Now that the routing.yml file from the bundle is being imported, add the new route that<br />

defines the URL of the page that you're about to create:<br />

# src/Acme/HelloBundle/Resources/config/routing.yml<br />

hello:<br />

pattern: /hello/{name}<br />

defaults: { _controller: AcmeHelloBundle:Hello:index }<br />

The routing consists of two basic pieces: the pattern, which is the URL that this route will<br />

match, and a defaults array, which specifies the controller that should be executed. The<br />

placeholder syntax in the pattern ({name}) is a wildcard. It means<br />

that /hello/Ryan, /hello/Fabien or any other similar URL will match this route.<br />

The {name} placeholder parameter will also be passed to the controller so that you can use its<br />

value to personally greet the user.<br />

The routing system has many more great features for creating flexible and powerful URL<br />

structures in your application. For more details, see the chapter all aboutRouting.<br />

Step 2: Create the Controller<br />

When a URL such as /hello/Ryan is handled by the application, the hello route is matched<br />

and theAcmeHelloBundle:Hello:index controller is executed by the framework. The<br />

second step of the page-creation process is to create that controller.<br />

The controller - AcmeHelloBundle:Hello:index is the logical name of the controller, and<br />

it maps to the indexAction method of a PHP class<br />

35

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!