Автозагрузка классов PHP, как сделать?

Всем привет. Пытаюсь сделать, автозагрузку классов для админки из папки admin, для остального из папки controllers.

Но что-то не получается. Что я делаю:

Маршрутизатор уже подключен $lib_path , далее делаю проверку, если layout == admin, тогда путь один, если нет, то другой. Код автозагрузки:
<?php

require_once (ROOT.DS.'config'.DS.'config.php');

function __autoload($class_name){
    $lib_path = ROOT.DS.'lib'.DS.strtolower($class_name).'.class.php';

    $model_path = ROOT.DS.'models'.DS.strtolower($class_name).'.php';

    if (file_exists($lib_path)){
        require_once ($lib_path);
    } 

  // Возвращает маршрут фронт или админки( default или admin)
    $layout = new Router($uri);
    $layout = $layout->getRoute();
    if ($layout == 'admin'){
        $controllers_path = ROOT.DS.'controllers/admin'.DS.str_replace('controller', '', strtolower($class_name)).'.controller.php';
    } else {
        $controllers_path = ROOT.DS.'controllers'.DS.str_replace('controller', '', strtolower($class_name)).'.controller.php';
    }

if (file_exists($controllers_path)){
        require_once ($controllers_path);
    } elseif (file_exists($model_path)){
        require_once ($model_path);
    } else {
      
       throw new Exception('Failed to include class' . $class_name);
    }


}


Получаю ошибку:

prntscr.com/h7o35w

Не могу понять, почему он пытается загрузить Class 'Router' , вместо того, чтобы выполнить условие.

Класс Router :

<?php

class Router {

    protected $uri;

    protected $controller;

    protected $action;

    protected $params;

    protected $route;

    protected $method_prefix;


    public function __construct($uri) {
        $this->uri = urldecode(trim($uri, '/'));

        // Получаем значения по умолчанию
        $routes = Config::get('routes');
        $this->route = Config::get('default_route');
        $this->method_prefix = isset($routes[$this->route]) ? $routes[$this->route] : '';
        $this->controller = Config::get('default_controller');
        $this->action = Config::get('default_action');
        // Разбиваем запрос на строку
        $uri_parts = explode('?', $this->uri);
        // Получаем путь ввида /controller/action/param1/param2/.../.../...
        $path = $uri_parts[0];

        $path_parts = explode('/', $path);

        // Проверяем есть ли в массиве $routes значение из текущей строки запроса
        if (in_array(strtolower(current($path_parts)), array_keys($routes))){
            // Если значение есть, записываем в переменную $this->route значение из текущего пути запрса
            $this->route = strtolower(current($path_parts));
            Config::set('aroute','strtolower(current($path_parts))');
            $this->method_prefix = isset($routes[$this->route]) ? $routes[$this->route] : '';
            array_shift($path_parts);
        }

        // Получаем контроллер - следующий элемент в массиве
        if (current($path_parts)) {
            $this->controller = strtolower(current($path_parts));
            array_shift($path_parts);
        }

        // Получаем вызываемый метод
        if (current($path_parts)){
            $this->action = strtolower(current($path_parts));
            array_shift($path_parts);
        }

        // Получаем параметры - оставшаяся часть запроса
        $this->params = $path_parts;

      //  echo "<pre>"; print_r($routes[$this->route]);
    }

    public function getUri()
    {
        return $this->uri;
    }

    public function getController()
    {
        return $this->controller;
    }

    public function getAction()
    {
        return $this->action;
    }

    public function getParams()
    {
        return $this->params;
    }

    public function getRoute()
    {
        return $this->route;
    }

    public function getMethodPrefix()
    {
        return $this->method_prefix;
    }

    public static function redirect($location){
        header("Location: $location");
    }



}


Что я делаю не так?
  • Вопрос задан
  • 526 просмотров
Пригласить эксперта
Ответы на вопрос 2
@Arik
Видно что подключили config, но не видно где подключили класс Router или он в этом же файле? или выше где-то инициализируется?
Ответ написан
alexey-m-ukolov
@alexey-m-ukolov Куратор тега PHP
Не могу понять, почему он пытается загрузить Class 'Router' , вместо того, чтобы выполнить условие.
Потому что вы ему об этом говорите при помощи new Router($uri).
Ответ написан
Ваш ответ на вопрос

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

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