PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Create your own framework... on top of the Symfony2 Components (part 7)

Note: This article was originally published at Planet PHP on 15 January 2012.
Planet PHP

One down-side of our framework right now is that we need to copy and paste the code in front.php each time we create a new website. 40 lines of code is not that much, but it would be nice if we could wrap this code into a proper class. It would bring us better reusability and easier testing to name just a few benefits.

If you have a closer look at the code, front.php has one input, the Request, and one output, the Response. Our framework class will follow this simple principle: the logic is about creating the Response associated with a Request.

As the Symfony2 components requires PHP 5.3, let's create our very own namespace for our framework: Simplex.

Move the request handling logic into its own Simple\Framework class:

A // example.com/src/Simplex/Framework.php A namespace Simplex; A use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\HttpKernel\Controller\ControllerResolver; A class Framework { protected $matcher; protected $resolver; A public function __construct(UrlMatcher $matcher, ControllerResolver $resolver) { $this-matcher = $matcher; $this-resolver = $resolver; } A public function handle(Request $request) { try { $request-attributes-add($this-matcher-match($request-getPathInfo())); A $controller = $this-resolver-getController($request); $arguments = $this-resolver-getArguments($request, $controller); A return call_user_func_array($controller, $arguments); } catch (Routing\Exception\ResourceNotFoundException $e) { return new Response('Not Found', 404); } catch (Exception $e) { return new Response('An error occurred', 500); } } } A

And update example.com/web/front.php accordingly:

A // example.com/web/front.php A // ... A $request = Request::createFromGlobals(); $routes = include __DIR__.'/../src/app.php'; A $context = new

Truncated by Planet PHP, read more at the original (another 7966 bytes)