Chad Minick
Software Developer

Option Pattern and avoiding Nulls pt. 3: Request Variables

January 7, 2013 Comments, ,

In Part 1 I introduced the Option pattern as a pattern to avoid using nulls. In Part 2 I showed an example of how this can be handy in method chaining. In this part I'll introduce how to use Option for request variables.

Request variables are supplied by the user. You can't rely on them to be there all the time. Something as simple as echo $_GET['search'] throws something like this:

PHP Notice:  Undefined index: search in ...

Doing naive echos like that can really fill your logs on a server quick. You can either turn Notices off (which you shouldn't), or you can find another safe way to get request variables. Here is an approach that works.

  echo isset($_GET['term']) ? $_GET['term'] : 'default';

Having to repeat $_GET['term'] twice is extremely ugly. In php 5.3, we have a short ternary like ?:, however that will not suppress the Notice, isset() is needed. This is another case where Option pattern can help.

  echo Option::create($_GET['term'])->getOrElse('default');

Much easier to read and flows much better. But since this is a very common use case to use Option for request variables, in my implementation I made a few static helpers.

  echo Option::_get('term')->getOrElse('default');
  echo Option::_post('username')->getOrElse('anonymous');
  
  //this works like $_REQUEST but without $_COOKIE,
  //$_GET always gets priority first
  //use _requestp($key) if $_POST needs priority
  echo Option::_request('term')->getOrElse('No Search Term Entered');

  header('Location: '.Option::_server('HTTP_REFERER')->getOrElse('http://example.org/'));

  //All these methods work with multidim arrays, for example: take $_GET['foo'][0];
  echo Option::_get('foo', 0)->getOrElse('default');

  //Don't forget you can map too!
  echo Option::_get('term')->map('htmlentities');

You can use Option during your form validation as well! Remember isEmpty() and isDefined() only care if the value is defined or not null. Empty strings, false and empty arrays are considered values here. I added another method hasLength() which returns false if the value isEmpty(), empty array, empty string. Personally I never agreed things like 0, false, '0' in php's empty function should return true on empty.

  $term = Option::_get('term');
  if($term->hasLength()) {
    //use it!
  } 

I hope you find this Option pattern useful! Happy coding!

Links

Option github poject: https://github.com/cythrawll/Option
Part 1
Part 2

comments powered by Disqus
Chad Minick | Software Developer
Twitter | Github | LinkedIn