@whiteleaf

Как правильно реализовать погрузку классов в PHP?

Здравствуйте,

Как Вы можете видеть с кода, я не долгое время изучаю программирование :), и надеюсь на понимание.
Сейчас пытаюсь разобраться с построением Роутинга и столкнулся с проблемой как мне динамически загружать классы с неймспейсами в PHP.

79997d75c1f042c3a29bf33d6c25d77f.png

Вот мой роутер :)

<?php


namespace library;
use controllers;


class Router {

    public $url;
    public $controller;
    public $method;


    public function __construct(){
        $this->includePath();

        if(!$this->parseUrl()){
            $this->controller = 'ControllerSite';
        }else{
            $this->controller = 'Controller'.ucfirst($this->url[0]);
        }

        $path = 'frontend/../controllers/'.$this->controller.'.php';

        if(file_exists($path))
        {
            unset($this->url[0]);
        }

        if(!isset($this->url[1])){
            $this->method = 'IndexMethod';
        }else{
            $this->method = $this->url[1];
        }

        $name = 'controllers\\'.$this->controller;

        $this->controller = new $name();
//        echo $this->controller;

    }
    private function includePath(){
        $paths = array(
            ROOT,
            get_include_path()
        );

        set_include_path(implode(PATH_SEPARATOR,$paths));
    }

    private function parseUrl(){
        if($_GET[r]){
            $parsed = explode('/',filter_var(rtrim($_GET[r],'/'),FILTER_SANITIZE_URL));
            $this->url = $parsed;
            return $this->url;
        }
    }

}


class Autoloader {

    static function autoload($className){

        if(!preg_match('/Controller/',$className)){
            if(file_exists(str_replace('\\','/',$className).'.php')){
                require_once $className.'.php';
            }
        }else{
            echo $className.'<br>';
            require_once ROOT.'../'.$className.'.php';
        }



    }

}
spl_autoload_register('library\Autoloader::autoload');
  • Вопрос задан
  • 2357 просмотров
Решения вопроса 1
Пригласить эксперта
Ваш ответ на вопрос

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

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