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?
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);
}
}