PHP Request Wrappers

January 5th, 2008

Here are a couple of basic PHP classes, which I find invaluable in reading external data into PHP

I often found in the development of a PHP site, that any logic involving calls to the $_POST or $_GET superglobals would involve a host of isset() checks, resulting in somewhat bloated if statements. Eventually I become so frustrated with this laborious logic, that I decided to write the PostVars and GetVars classes and hopefully make my life alot easier for myself.

The resulting classes has not only cut down on development time of form parsing scripts, but also made them more readable to subsequent developers. Other key benefits I’ve found:

  • Now only one point in a script that defines the superglobal reference, making it easy to alter if required.
  • No need to call isset() (or empty() etc) if you want to reference/access a superglobal array. Saving time in writing if statements and reducing the chance of warning errors.
    // No need for the following laborious style of if statements
    if(isset($_POST["id"] && $_POST["id"]) { // Something here }
    
  • Adds future flexibility from the vantage point of OOP development.

Download the PHP source code and example pack (.zip 8Kb)

Examples

In order to begin using the classes, all you need to do is un-package the example ZIP into a directory (preferably outside the public root) and include (or require - my preferred method) the classes into the top of your script. Then you simply instantiate either a PostVar or GetVar object and start accessing via the get() method.

require_once("/path/to/post.vars.class.php");
require_once("/path/to/get.vars.class.php");

// Instantiate new PostVars (or GetVars) object
$vars = new PostVars();

// Access item (returns either value or boolean false)
echo($vars->get("example"));

Download the PHP source code and example pack (.zip 8Kb)