@dev400

Есть ли косяки в роутинге?

Простой роутинг
<?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();
	}
}


Что на ваш взгляд нужно убрать/добавить?
  • Вопрос задан
  • 228 просмотров
Пригласить эксперта
Ответы на вопрос 2
@IceJOKER
Web/Android developer
Лень читать тело методов, но мне не нравится конструктор, не перегружайте его лишними данными, он обычно служит для инициализации переменных и т.д. остальную логику перенесите в методы, так легче будет поддерживать код
Ответ написан
Комментировать
trevoga_su
@trevoga_su
почитай - www.phpinfo.su/articles/practice/chpu_na_php.html

вот это
if ( Logic::get() === "frontend") {

if ( $this->uri[1] === "news"

if ( $this->uri[1] === "catalog"

лютый треш. неужели сам не видишь, что это говнокод хардкод? Куча стремных if-ов, монолитность, непереносимость. Все делается ГОРАЗДО проще. Прочитай статью.

if (Logic::get() === "backend") {
нет никакого frontend и бекенд. с точки зрения роутинга - это просто разные контроллеры.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы