21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Symfony2 – Franz Jordán 2011<br />

Now, every request is handled exactly the same. Instead of individual URLs executing different<br />

PHP files, the front controller is always executed, and the routing of different URLs to different<br />

parts of your application is done internally. This solves both problems with the original<br />

approach. Almost all modern web apps do this - including apps like WordPress.<br />

Stay Organized<br />

But inside your front controller, how do you know which page should be rendered and how can<br />

you render each in a sane way? One way or another, you'll need to check the incoming URI and<br />

execute different parts of your code depending on that value. This can get ugly quickly:<br />

// index.php<br />

$request = Request::createFromGlobals();<br />

$path = $request->getPathInfo(); // the URL being requested<br />

if (in_array($path, array('', '/')) {<br />

$response = new Response('Welcome to the homepage.');<br />

} elseif ($path == '/contact') {<br />

$response = new Response('Contact us');<br />

} else {<br />

$response = new Response('Page not found.', 404);<br />

}<br />

$response->send();<br />

Solving this problem can be difficult. Fortunately it's exactly what Symfony is designed to do.<br />

The Symfony Application Flow<br />

When you let Symfony handle each request, life is much easier. Symfony follows the same simple<br />

pattern for every request:<br />

7

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

Saved successfully!

Ooh no, something went wrong!