I've built a simple class RequestHandler
that does exactly what I want without any extras I won't be utilizing. When needed I will expand. I'm passing this object to my Router class, to route URls to the correct controller. I will also take any suggestions!
How is the readability?
Good idea to make it a singleton? There will always be 1 request to process at a time.
What about dependency injection? I didn't utilize dependency injection with this class. How else would I get the URI without using $_SERVER['REQUEST_URI']
or any other similar $_SERVER
variable. So I don't see why I would inject it, while there are no other ways.
class RequestHandler
{
private $rawUri;
private $cleanUri;
private $method;
private $controller;
private $action;
private $params = [];
public function __construct()
{
$this->rawUri = $_SERVER['REQUEST_URI'];
$this->cleanUri = preg_replace(['#/+#', '(\.\./)'], '/', trim($this->rawUri, '/'));
$this->method = $_SERVER['REQUEST_METHOD'];
$this->parseUri();
}
private function parseUri()
{
//parse "/controller/action/param1/param2/..." format
$parts = explode('/', $this->cleanUri);
$parts = array_filter($parts);
sort($parts);
if ($parts) {
$this->controller = ucfirst(array_shift($parts)) . 'Controller';
$this->action = array_shift($parts);
$this->params = ($parts) ? $parts : null;
}
}
public function getRawUri()
{
return $this->rawUri;
}
public function getCleanUri()
{
return $this->cleanUri;
}
public function getMethod()
{
return $this->method;
}
public function getController()
{
return $this->controller;
}
public function getAction()
{
return $this->action;
}
public function getParams()
{
return $this->params;
}
}