Sajjuks Harry Porter Store

Thursday 9 January 2014

The Journey from the Request to the Response

Like HTTP itself, the Request and Response objects are pretty simple. The hard part of building an application is writing what comes in between. In other words, the real work comes in writing the code that interprets the request information and creates the response.
Your application probably does many things, like sending emails, handling form submissions, saving things to a database, rendering HTML pages and protecting content with security. How can you manage all of this and still keep your code organized and maintainable?

The Front Controller

Traditionally, applications were built so that each "page" of a site was its own physical file:
1
2
3
index.php
contact.php
blog.php
There are several problems with this approach, including the inflexibility of the URLs (what if you wanted to change blog.php to news.php without breaking all of your links?) and the fact that each file must manually include some set of core files so that security, database connections and the "look" of the site can remain consistent.
A much better solution is to use a front controller: a single PHP file that handles every request coming into your application. For example:
/index.php executes index.php
/index.php/contact executes index.phpNow, every request is handled exactly the same way. Instead of individual URLs executing different PHP files, the front controller is always executed, and the routing of different URLs to different parts of your application is done internally. This solves both problems with the original approach. Almost all modern web apps do this - including apps like WordPress.

Stay Organized

/index.php/blog executes index.php
Using Apache's mod_rewrite (or equivalent with other web servers), the URLs can easily be cleaned up to be just /, /contact and /blog.
Symfony was created to solve these problems so that you don't have to.
Inside your front controller, you have to figure out which code should be executed and what the content to return should be. To figure this out, you'll need to check the incoming URI and execute different parts of your code depending on that value. This can get ugly quickly:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// index.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();
$path = $request->getPathInfo(); // the URI path being requested

if (in_array($path, array('', '/'))) {
    $response = new Response('Welcome to the homepage.');
} elseif ($path == '/contact') {
    $response = new Response('Contact us');
} else {
    $response = new Response('Page not found.', Response::HTTP_NOT_FOUND);
}
$response->send();
Solving this problem can be difficult. Fortunately it's exactly what Symfony is designed to do.


No comments:

Post a Comment