How can I write my code more efficient (not repeating same code)?
And is there a solution that simplifies the way of having to create a lot of dependency objects over and over again whenever I instantiate a new class (as seen in the load method)?
Any suggestions are welcome.
class Router
{
private $request;
private $cleanUri;
# control attributes
private $controller;
private $action;
private $params = [];
public function __construct(Request $request)
{
$this->request = $request;
$this->cleanUri = preg_replace(['#/+#', '(\.\./)'], '/', trim($request->getUri(), '/'));
$this->parseUri();
$this->load();
}
private function parseUri()
{
$parts = explode('/', $this->cleanUri);
$this->controller = ($this->cleanUri !== '' ? ucfirst(array_shift($parts)) : 'Index') . 'Controller';
$this->action = array_shift($parts);
$this->params = !empty($parts) ? $parts : null;
}
private function load()
{
if (class_exists($this->controller)) {
if (empty($this->action)) {
$this->action = 'index';
} elseif ($this->action !== 'index' && method_exists($this->controller, $this->action)) {
//$action value stays the same
} else {
if (class_exists('_404Controller')) {
$controller = new _404Controller();
$controller->index();
} else {
throw new Exception('404 controller not found. Page doesn\'t exist for: ' . $this->request->getUri());
}
}
$controller = $this->controller;
//create dependencies
$db = new Database();
$user = new User($db, $this->request);
$menu = new MenuHelper($this->request, $user);
$controller = new $controller($this->request, $user, $menu);
$action = $this->action;
$controller->$action();
} else {
if (class_exists('_404Controller')) {
$controller = new _404Controller();
$controller->index();
} else {
throw new Exception('404 controller not found. Page doesn\'t exist for: ' . $this->request->getUri());
}
}
}
}