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;
    }
}
\$\endgroup\$
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.