views:

101

answers:

5

I find in my PHP pages I end up with lines and lines of code that look like this:

$my_id = isset($_REQUEST['my_id']) ? $_REQUEST['my_id'] : '';
$another_var = isset($_REQUEST['another_var']) ? $_REQUEST['another_var'] : 42;
...

Is there a better, more concise, or more readable way to check this array and assign them to a local variable if they exist or apply a default if they don't?

EDIT: I don't want to use register_globals() - I'd still have the isset problem anyway.

+4  A: 

a better method might be to create a singleton/static class to abstract away the details of checking the request data.

Something like:

class Request {

  private $defaults = array();
  private static $_instance = false;

  function getInstance () {
    if (!self::$_instance) {
     $c = __CLASS__;
      self::$_instance = new $c;
    }
    return self::$_instance;
  }

  function setDefaults($defaults) {
    $this->defaults = $defaults;
  }

  public function __get($field) {
    if (isset($_REQUEST[$field]) && !empty($_REQUEST[$field])) {
        return $_REQUEST['field'];        
      } elseif (isset($this->defaults[$field])) {
        return $this->defaults[$field];
      } else {
        return ''; # define a default value here.
      }
   }
}

you can then do:

# get an instance of the request
$request = Request::getInstance();

# pass in defaults.
$request->setDefaults(array('name'=>'Please Specify'));

# access properties
echo $request->name;
echo $request->email;

I think this makes your individual scripts loads cleaner and abstracts away the validation etc. Plus loads of scope with this design to extend it/add alternate behaviours, add more complicated default handling etc etc.

benlumley
Any example of how that would work? It seems like it would obfuscate what is going on. Maybe I'm not following...
BabyCakes
yeah - filled it out now!
benlumley
I do like this after all - :-)
BabyCakes
+1  A: 

Is the set of variables you're expecting known at the time of the script's writing, or do you want to do this for an arbitrary set of values? If the former is true, you could do something like this:

# This array would hold the names of all the variables you're expecting
# and a default value for that variable name
$variableNames = array (...); 
foreach ($variableNames as $key => $default) {
    if (isset ($_REQUEST[$key])) $$key = $_REQUEST[$key];
    else $$key = $default;
}

Basically, this takes advantage of PHP's ability to evaluate variables to create other variables (hence the double-dollar for $$key--this means create a new variable whose name is the value of $key).

I haven't yet come up with a good solution to the latter situation.

B.R.
+4  A: 

How about wrapping it in a function?

<?php

function getPost($name, $default = null) {
    return isset($_POST[$name]) ? $_POST[$name] : $default;
}
Glass Robot
I like this one but my daily vote limit is reached. I was in the middle of writing the same answer.
Brian Ramsay
The only thing I would change is function name, to something shorter. I think post() sounds nicer.
Thinker
+2  A: 

First, use $_POST for POSTed variables. $_REQUEST is a mashup of many different incoming variables, not just $_POST and could cause problems.

One solution for your question would be to create a function that handles the isset() logic.

function ForceIncomingValue($Key, $Default) {
    if (!isset($_POST[$Key]))
         return $Default;
    else return $_POST[$Key];
}
sirlancelot
yeah, sometimes I use GET, sometimes POST so I just use _REQUEST
BabyCakes
Again, _REQUEST cannot be trusted as it also includes _COOKIE data. See the documentation: http://php.net/request
sirlancelot
interesting, I didn't know that
BabyCakes
+2  A: 

first of all, NEVER use the $_REQUEST variable, it'll lead to bugs and other problems during development

function getPOST($key) {
    if(isset($_POST[$key])) {
        return $_POST[$key];
    }
}

note that this code leaves the variable empty when $_POST[$key] was not set

you could also adapt that code to enable you to instead provide you with a (sensible) default when the value could not be loaded.

function getPOST($key, $default = NULL) {
    if(isset($_POST[$key])) {
        return $_POST[$key];
    } else {
        return $default;
    }
}
alexanderpas
we've used REQUEST all over the place for years and I haven't seen any problems. though we don't use cookies... maybe that has something to do with it.
BabyCakes