Screencast Series – Creating Own PHP Framework Using Symfony2 Components – Episode 3

Recap

In the previous episodes we’ve formed a solid basis for our framework:

  1. Installed the Composer – Dependency Injection Manager
  2. Installed two Symfony2 Components – Class Loader and HttpFoundation

In this episode

In this episode we’ll create the heart of our framework – the front controller. It’s primary role in our framework will be dispatching HTTP responses based on the HTTP requests (URL the client has called). In order to do that we’ll be reordering the files into the logical directory structure and writing some amazing code. Enjoy!

Show notes

File Structure

We’ll essentially move the code of our application into the /src directory. With the subdirectory /src/pages to get hold of all the pages (templates) we’ll be creating. Third party libraries – Symfony2 Components and such – will be stored in directory /vendor. And our front controller will reside under /web.

The Front Controller

The goal is to map the URL entered by the client to the file. So /bye will be dispatched to /src/pages/bye.php

<?php
// /web/front.php
require_once __DIR__.'/../src/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();
$response = new Response();

// Mapper
$map = array(
    '/hello' => __DIR__ . '/../src/pages/hello.php',
    '/bye'   => __DIR__ . '/../src/pages/bye.php',
);

$path = $request->getPathInfo();
if (isset($map[$path])) {
    ob_start();
    require $map[$path];
    $response->setContent(ob_get_clean());
} else {
    $response->setStatusCode(404);
    $response->setContent('Oooops, we did not find this page!');
}

$response->send();

Web Server Configuration

To secure our application and just to be cool we’ll restrict the access to the file structure. Since the front controller will dispatch all the inbound calls (URLs) and include the files to be displayed, it makes sense to have it as a single access point in our application. So, we’ll tell Apache to consider /web directory as the web root directory.
So the hello.php page will be accessible via:

www.example.com/front.php/hello

and not directly via

www.example.com/src/pages/hello.php
andremaha

About The Author

2 Comments

  1. Denis says:

    Hello Andre,
    I have a friendly advice, nothing regarding technical stuff.

    First, I like your approach and energy you put in this. The only thing I noticed in your videos, you have to work on your English a little, by (try to) avoiding this thinking gaps, like “ahmm”, “aaa” etc.

    Everything else is perfect!!

    Thanks

  2. andremaha says:

    Dear Denis,

    thank you for your feedback. It’s always nice to hear the word of advice. The two closing videos are in production right now, and I will try to reduce the thinking gaps.

Leave A Reply