1
\$\begingroup\$

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;
 }
}
asked Apr 30, 2014 at 15:45
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Just a quick observation I have made here, and this is by no means a full review, but you have some dead code here:

if ($parts) {
 $this->controller = ucfirst(array_shift($parts)) . 'Controller';
 $this->action = array_shift($parts);
 $this->params = ($parts) ? $parts : null;
}

It will only enter the if-block if $parts is true, and when assigning to $this->params you check it again, but it can never be null.

Therefore you should just assign $this->params = $parts;

Overall the readability of the code looks fine to me.

answered Apr 30, 2014 at 15:55
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.