Skip to content

Instantly share code, notes, and snippets.

@jwdunne
Created September 28, 2011 07:01
Show Gist options
  • Save jwdunne/1247189 to your computer and use it in GitHub Desktop.
Save jwdunne/1247189 to your computer and use it in GitHub Desktop.
A request class
<?php
/**
* Request Class
*
* Allows code to use only the HTTP request variables they need
*/
class Request {
const GET = 'GET';
const POST = 'POST';
private $allowed;
private $type;
public static function requires($type) {
$args = func_get_args();
// Remove type from the args array
unset($args[0]);
// default to 'get' requests
$type = strtoupper($type);
if ($type != self::GET || $type != self::POST) {
$type = self::GET;
}
// Make sure only strings are used here
// I use an assoc. for constant lookup
$allowedVars = array();
foreach ($args as $value) {
if (is_string($value)) {
$allowedVars[$value] = TRUE;
}
}
return new Request($type, $allowedVars);
}
public function __construct($type, $allowed) {
$this->type = $type;
$this->allowed = $allowed;
}
/**
* Allows users to get get/post vars like a member rather
* than having to call a method all the time.
*
* @param string $name This is the key of the request var (name attribute in HTML)
* @return mixed Returns NULL if nothing found else returns what is requested
*/
public function __get($name) {
if ($this->isAllowed($name)) {
if ($this->isType(self::GET)) {
return $_GET[$name];
}
return $_POST[$name];
}
return NULL;
}
/**
* Complementary to the above method, allows user to check if a member (Request var) is
* set.
*
* @param string $name This is the key of the request var (name attribute in HTML)
* @return boolean Either true or false, dependant on if the var is set.
*/
public function __isset($name) {
if ($this->isAllowed($name)) {
if ($this->isType(self::GET)) {
return isset($_GET[$name]);
}
return isset($_POST[$name]);
}
return FALSE;
}
/**
* Check the type (either GET or POST)
*/
private function isType($type) {
return $this->type == $type;
}
/**
* Check if this object is allowed this var
*/
private function isAllowed($name) {
return isset($this->allowed[$name]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment