Answer the question
In order to leave comments, you need to log in
Are there jambs in routing?
Simple routing
<?php
namespace Common;
use Backend;
use Frontend\Controllers;
class Router
{
private $uri = [];
/**
* Router constructor.
*/
public function __construct() {
$route = $this->getController();
$method = $route['method'];
$controller = Logic::get()."\\controllers\\" . $route['controller'];
$obj = '';
if ( class_exists($controller) ) {
$obj = new $controller;
} else {
$this->notFound();
}
if ( method_exists($obj, $method) ) {
if ( empty($route['params']) ) {
$obj->$method();
} else {
if ( !$obj->$method($route['params']) ) {
$this->notFound();
}
}
} else {
$this->notFound();
}
}
/**
* @return mixed
*/
private function getController()
{
$this->uri = explode('/', $_SERVER['REQUEST_URI']);
$array['controller'] = 'index';
$array['method'] = 'index';
$array["params"] = [];
if ( Logic::get() === "frontend") {
if ( $this->uri[1] === "news" && !empty($this->uri[2]) ) {
$array['controller'] = "news";
$array['method'] = "getSingle";
$array["params"] = [ 0 => $this->uri[2] ];
return $array;
}
if ( $this->uri[1] === "catalog" && !empty($this->uri[2]) ) {
$array['controller'] = "catalog";
$array['method'] = "categoryView";
$array["params"] = [ 0 => $this->uri[2] ];
if ( !empty($this->uri[3]) ) {
$array['method'] = "singleView";
$array["params"] = [ 0 => $this->uri[2], 1 => $this->uri[3] ];
}
return $array;
}
if (!empty($this->uri[1])) {
$array['controller'] = $this->uri[1];
}
if (!empty($this->uri[2])) {
$array['method'] = $this->uri[2];
}
}
if (Logic::get() === "backend") {
if (!empty($this->uri[2])) {
$this->uri[2] = strtok($this->uri[2], "?");
$array['controller'] = $this->uri[2];
}
if (!empty($this->uri[3])) {
$this->uri[3] = strtok($this->uri[3], "?");
$array['method'] = $this->uri[3];
}
}
return $array;
}
/**
* 404
*/
public function notFound() {
$controller = Logic::get()."\\controllers\\error";
$obj = new $controller;
$obj->index();
}
}
Answer the question
In order to leave comments, you need to log in
Too lazy to read the body of methods, but I don't like the constructor, don't overload it with unnecessary data, it usually serves to initialize variables, etc. transfer the rest of the logic to methods, so it will be easier to maintain the code
read - www.phpinfo.su/articles/practice/chpu_na_php.html
here it is
if ( Logic::get() === "frontend") {
if ( $this->uri[1] === "news"
if ( $this->uri[1] === "catalog"
Very weak.
The router should not be busy loading controller files. He is a routing, not a loader.
The implementation of routing and its configuration are mixed.
The only comment "@return mixed" is beyond evil.
Too inflexible.
"namespace Common;" Do you use the word common as a synonym for trash?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question