Below you can find the constructor method and related fields of the main class of my REST API (note that the class contains more code than displayed) written in PHP 7.1. It does various things with the HTTP-request. It starts with getting the arguments and then it gets the method in which the request is made (like POST or GET). The request gets trimmed of tags and that gets saved back into the instance/member variable $this->request.
Now, to my best knowledge, $this->request in PHP always points to the HTTP-request when a HTTP-request has just been made. The code can only get here when a HTTP-request has been made and $this->method has been filled ($this->method = $_SERVER['REQUEST_METHOD'];).
In other words, $this->method should always exist, but I keep getting the 'Field declared dynamically' warning:
Is it okay to just ignore the warning or is there a best practice to deal with it?
Other tips to improve my code are welcome too. I've 'learned' PHP back in version 4 (I used it for uni once). I struggle with the OO concepts since introduced in a language where so much is allowed.
class BaseAPI {
protected $method = '';
protected $endpoint = '';
protected $verb = '';
protected $args = Array();
public function __construct($request)
{
header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");
header("Content-Type: application/json");
$this->args = explode('/', rtrim($request, '/'));
$this->endpoint = array_shift($this->args);
if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) {
$this->verb = array_shift($this->args);
}
$this->method = $_SERVER['REQUEST_METHOD'];
if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
$this->method = 'DELETE';
} else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
$this->method = 'PUT';
} else {
throw new IncorrectHeaderException("Unexpected Header");
}
}
switch ($this->method) {
case 'DELETE':
case 'PUT':
// don't do anything yet
case 'POST':
$this->request = $this->_cleanInput($_POST);
break;
case 'GET':
$this->request = $this->_cleanInput($_GET);
break;
default:
throw new IncorrectMethodException('Invalid Method');
break;
}
}
private function _cleanInput($data)
{
$cleaned_input = Array();
if (is_array($data)) {
foreach ($data as $k => $v) {
$cleaned_input[$k] = $this->_cleanInput($v);
}
} else {
$cleaned_input = trim(strip_tags($data));
}
return $cleaned_input;
}
}
