Question

Should I just call them by their name $_GET, $_POST, $_SESSION //etc, or should I wrap them in a class? For example for the POST superglobal, so that it returns false if a certain array index is not set?

Let's say I have a Validator class. So I have to pass through every field like so $_POST['name'] but if it's not set it will return an undefined index error. But if it would return false instead that wouldn't happen.

Is there any preferred way or best practice to use superglobals?

Was it helpful?

Solution

You might create an Input class that takes care of that. Just a stub:

class Input
{
   private $_post;
   private $_get;
   private $_session;
   private $_server;

   public function __construct()
   {
      $this->_post = $_POST;
      $this->_get = $_GET;
      // and so on
   }

   public function post($key = null, $default = null)
   {
       return $this->checkGlobal($this->_post, $key, $default);
   }

   public function get($key = null, $default = null)
   {
       return $this->checkGlobal($this->_get, $key, $default);
   }

   // other accessors

   private function checkGlobal($global, $key = null, $default = null)
   {
     if ($key) {
       if (isset($global[$key]) {
         return $global[$key];
       } else {
         return $default ?: null;
       }
     }
     return $global;
   }
}

Sample usage:

$input = new Input();
print_r($input->post()); // return all $_POST array
echo $input->post('key'); // return $_POST['key'] if is set, null otherwise
echo $input->post('key', 'default'); // return 'default' if key is not set

Of course you need to expand this further, but that's the idea.

Edit:

if you feel better, you can make this part of your request handler:

namespace App;

use App\Input;

class Request
{
   private $input;

   public function __construct()
   {
      $this->input = new App\Input();
   }

   public function post($key = null)
   {
      return $this->input->post($key);
   }
}

OTHER TIPS

You Could have an Application Object, and Assign Superglobals to them

class Request {
    public static function GetUrlParameter($key, $default = '') {
        return isset ($_GET[$key]) ? $_GET[$key] : $default;
    }
}

$app = new Application();
$app->Page = Request::GetUrlParameter('page', 'home');
$app->PostBacks = $_POST;
$app->Render();

Sure PostBacks ist quick and dirty. You want to have a Module Object for each Module/Formular, where you can assign your PostBacks (i. e. Username, Password) like Page to the Application Object.

Edited. Added part of a Request Class i have written for my needs, thanks for Dave's Comment.

Upvoted Question. I am also interested in alternative Solutions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top