Camber – a minimalist LAMP framework

Over the past few months I’ve been adding code to this previously unnamed LAMP framework, but I’ve honestly been reluctant to call it a framework. That’s what it is though, so instead of constantly referring to it as “my little minimalist pseudo-framework”, I decided to give the thing a name. I’ve been mulling it over for several months now, and finally settled on Camber as the name. I wanted to be sure that it was easy enough to remember, but also meaningful to the overall goal of the project. According to Google:

Camber: The curvature of a structural member for the purpose of offsetting the deflection when loads are applied.

Camber is not a complex idea, nor is it difficult to implement where it’s needed. It’s used in many everyday load-bearing applications; the wheels of a car, the shape of skis and snowboards, the bottom of a bridge, the shape of a wing. The performance of each of these is greatly enhanced – if not utterly dependent – on something as simple as the underlying negative curvature.

Sounds like a pretty good description of a web application framework, eh?

Unfortunately, I’ve been really slack about keeping this here blog up to date with the actual code I’ve been writing. I have a tendency to drone on and on about each concept of the system, so I think I need to take smaller bites. One post per day maybe, with no more than 2 or 3 snippets of code.

Getting organized with a new domain name

I decided to move my blog from the old address ( to one that is named after me, Drew C King, in order to get a bit more organized. I’ve been using “cholmon” as a pseudonym across the internet for many years, but it’s not exactly the easiest name for folks to remember, or to spell correctly. My goals in doing this are not only to have a domain name that is easier to spell, but also to stake a more real-life claim over the content I’m posting, and to make that content more SEO friendly so that interested people can find it as quickly as possible.

I’m also getting much more interested in search engine optimization in general. Coming from a background based primarily in development and system administration, this area is pretty new to me. While it seems to be mostly common sense, there are a plethora of subtleties – hence the O in SEO – whose importance would be pretty difficult to gauge without the help of SEO folks like Matt Cutts over at Google.

So in addition to using this blog as a means of getting my PHP-related ideas and experiences down on virtual paper, I’m also going to use it as a way of trying out some optimization techniques to see first hand what works and what doesn’t.

Evolving Framework, Step 4: Handle requests with a request handler

So, picking up from where I left off in Step 3, cleaning up the server-side, we’ve now got a simple HTML form that sends a clean request into the server, and a nice little Request class to make the incoming data easy to work with. To jog your memory, the form looks like:

<form action="/session" method="post">
  <input type="hidden" name="method" value="put" />
  Username: <input type="text" name="username" /><br />  
  Password: <input type="password" name="password" /><br />  
  <input type="submit" value="Login..." />  

When the form gets submitted, index.php creates a new Request object to encapsulate all the request data. But once the Request is all set up, then what? My goal here is to log the user into their account, or if I read the HTTP request the way I intended it to be interpreted, I want to:

Create a session on the server with the specified username and password.

Well, the most straightforward way to do this would be to just stick all the input-sanitizing, database-connecting, user-authenticating logic directly after the Request object is born, making index.php look something like this:

    include 'Request.php';
     * create the request
    $req = new Request();
     * pull the necessary data out of the request
     * i.e., 
     *  username=drew&password=qwerty
     * In real life, error checking and validation would be a good idea here
    $username = $req->params['username'];
    $password = $req->params['password'];
     * Connect to the db and see if the username/password combo is valid
     * I like mysqli:
    $db = new MySQLi('localhost', 'dbuser', 'securepassword', 'dbname');
    $sql = 'SELECT UserID FROM Users WHERE Username = ? AND Password = MD5(?)';
    if ($stmt = $db->prepare($sql))
        $stmt->bind_param('ss', $username, $password);
        if ($userID == 0) {
            die("access denied, try again.");
        } else {
            die("access granted! userid: $userid");

Hopefully it is obvious to you that putting all that code smack in the middle of the site’s one-and-only index.php would suck really badly. Afterall, index.php has to handle every single request. The only reasonable way to go about this is to have some sort of dynamically loaded request-examining code. I’ll have to decide on some standard way to look at every request, and depending on the method, path, and parameters, load up some request-specific logic on the fly. Something to this affect:

    include 'Request.php';
    include 'RequestHandler.php';
    $request = new Request();
     * Create this magical object that "handles" the given $request object
    $handler = new RequestHandler($request);
     * Tell the RequestHandler to do the dirty work

This would get the clutter out of index.php and into the RequestHandler object. Of course, the RequestHandler is a black box at this point, but the idea is to use that class in such a way as to load up and run the request-specific logic, i.e., form validation, database querying, and of course output.

Step 5 will consider what exactly the RequestHandler needs to do, and how we might need to modify our currently bare-bones index.php bootstrap.

Evolving Framework, Step 3: Cleaning up the server-side

Once I had my virtual host set up to route all requests into a single script, I then had to figure out what to do with each request. I knew that the essential request information was available in the $_SERVER autoglobal, but I wanted a cleaner way of dealing with the request. So I put together a very simple Request class, which I saved in the document root as Request.php:

class Request 
    public $method; 
    public $url; 
    public $parameters = array();  
    public function __construct() 
        $this->method = $_SERVER['REQUEST_METHOD']; 
        $this->url = $_SERVER['SCRIPT_URI']; 
        $this->parameters = $_REQUEST; 

Continue reading

Evolving Framework, Step 2: Make PHP understand the clean URL

So why am I bothering with “clean” URLs? For several reasons really. For one thing, they look nicer than un-clean URLs. I would much rather get rid of something like, this:

and instead use something like this:

But aesthetics aside, why should I bother? My reason is inspired by Roy Fielding’s REST. I won’t try to get into the guts of it here, partly because there’s alot to it, and partly because my grasp of it is far from complete. Regardless, what I’ve taken from my brief introduction to it is a resolution to build applications from a resource-centric point of view, as opposed to a functional, process-centric point of view. Instead of building a collection of scripts that expect data to be passed in so that they can spit data out, I want to try to build a system of resources that can be manipulated.

In order to manipulate a resource, three essential pieces of information are required:

  1. The location of the resource in question (the URL)
  2. The type of manipulation to be performed on the resource (HTTP method; PUT, GET, POST, DELETE)
  3. The data needed to perform the manipulation (request parameters)

One thing I noticed at this point was that the request method could essentially take the place of the action parameter I’ve seen being passed around in so many frameworks (and which I’m guilty of having used in the past). With any resource in mind (e.g., user object, news article, forum thread, photo album, etc), PUT, GET, POST, and DELETE can do pretty much anything you need, or at least imply your intention to do pretty much anything.

Also, those four major request methods map pretty conveniently to CRUD:

  • GET == READ

I figured a good place to start trying to implement something like this would be structuring the URLs in such a way that they look like nouns. So an old school login form may have looked like:

<form action="/login.php" method="post">
  Username <input type="text" name="username" /><br />
  Password <input type="password" name="password" /><br /> 
  <input type="submit" value="Login..." />

The problem with that code (RESTfully clean URLs in mind) is the action and the method. The form is POSTing the username and password to login.php. But is login.php really the resource that I want to POST to? If I replace the word POST with the word UPDATE, it makes a little bit less sense. I’m not updating login.php itself. That script doesn’t represent a resource of any kind; it’s just a procedure, a machine that takes data in one side and spits data out the other.

So I took a step back and thought about what I was actually trying to accomplish. I wanted to authenticate a user; check their username and password against the database, and if it matched a valid user record then stick their information in the session for use throughout their visit.

In other words, my goal was to create an authenticated user session. Since “create” maps to the PUT method, I decided to change the form around to look like this:

<form action="/session" method="put">
  Username <input type="text" name="username" /><br />
  Password <input type="password" name="password" /><br /> 
  <input type="submit" value="Login..." /> 

My intention was to provide the following information to the web server:

  • Location of the resource: /session
  • Operation to be performed on the resource: PUT (i.e., create)
  • Additional information needed to operate on the resource: username and password
    • It seemed a good bit more logical this way. Instead of telling the web server, “here’s a username and password that I want the login script to authenticate“, I’m telling it, “I want to create a new session based on this username and password“.

      The tricky part was actually writing the code to interpret the request in such a way that this actually happened like I wanted. Step 3 is coming up next. In it I’ll explain my initial approach to solving my RESTlessness, and some unexpected problems I ran into along the way.

Evolving Framework, Step 1: mod_rewrite + PHP = Clean URLs

Using clean URLs with Apache is fairly simple with mod_rewrite’s help. I’d be the first to admit that rewrite rules can be as

ridiculously complicated as they are powerful, but plenty of people have already admitted this. Luckily, what I’m trying to accomplish is not very difficult, mod_rewrite-wise. Taking a forum as an example, you might see URLs like:

  • – site’s main page
  • – list of forums
  • – list all threads in general forum
  • – list all posts in some_arbitrary_topic thread

To handle URLs similar to this, I set up the virtual host container to simply rewrite every request through a single PHP script, which I’ll lovingly call index.php. To start off, it just looks like this:


Pretty basic and useless. It just dumps out everything about the request and the server environment in an easy-to-read manner. But we have to tell Apache to use index.php for everything, so the virtual host container in Apache’s config file looks like this:

<VirtualHost *:80>
    DocumentRoot    /www/vhosts/
    RewriteEngine   On 
    RewriteRule     /*\.(css|js|gif|png|jpe?g)$ - [NC,L] 
    RewriteRule     ^/* /index.php
    <Directory "/www/vhosts/">
                AllowOverride None 
                Order allow,deny 
                Allow from all 

(To read up on configuring virtual hosts and figuring out mod_rewrite, check out

Those three rewrite directives accomplish the following:

  1. RewriteEngine On: tells Apache to expect some rewrite rules
  2. RewriteRule /*\.(css|js|gif|png|jpe?g)$ – [NC,L]: don’t rewrite images, stylesheets, or javascripts.
  3. RewriteRule ^/* /index.php: any other request should just run index.php

So, for instance, if you type into your browser’s address bar, the request would get sent into index.php and you’d see the following (pay particular attention to the highlighted lines):

    [SCRIPT_URL] => /some/made/up/path 
    [SCRIPT_URI] => 
    [HTTP_ACCEPT] => image/gif, image/x-xbitmap, image/jpeg, */* 
    [HTTP_ACCEPT_LANGUAGE] => en-us 
    [HTTP_UA_CPU] => x86 
    [HTTP_ACCEPT_ENCODING] => gzip, deflate 
    [HTTP_USER_AGENT] => Mozilla/4.0 (compatible; MSIE 7.0) 
    [HTTP_HOST] => 
    [HTTP_CONNECTION] => Keep-Alive 
    [PATH] => /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin 
    [SERVER_SOFTWARE] => Apache/2.2.0 (Unix) PHP/5.2.0  
    [SERVER_NAME] => 
    [SERVER_ADDR] => 
    [SERVER_PORT] => 80 
    [REMOTE_ADDR] => 
    [DOCUMENT_ROOT] => /www/vhosts/ 
    [SERVER_ADMIN] => [no address given] 
    [SCRIPT_FILENAME] => /www/vhosts/ 
    [REMOTE_PORT] => 57503 
    [QUERY_STRING] => this=that&foor=bar 
    [REQUEST_URI] => /some/made/up/path?this=that&foor=bar 
    [SCRIPT_NAME] => /some/made/up/path
    [PHP_SELF] => /some/made/up/path 
    [REQUEST_TIME] => 1169876370 

At this point, the main parts of the request that I’m interested in are:

  • The method (GET)
  • The script name (/some/made/up/path)
  • The query string (this=that&foor=bar)

Step 2 will be up here in the next day or so. In it, I’ll modify index.php so that it parses those three pieces of information and decides what to do with the request. OMG STAY TUNED LOL!!!