W
W
whiteleaf2014-10-06 21:00:43
PHP
whiteleaf, 2014-10-06 21:00:43

How to properly implement class loading in PHP?

Hello,
As you can see from the code, I haven't studied programming for a long time :), and I hope you understand.
Now I'm trying to figure out how to build Routing and I ran into a problem how can I dynamically load classes with namespaces in PHP.
79997d75c1f042c3a29bf33d6c25d77f.png
Here is my router :)

<?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');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Volodymyr Godyak, 2014-10-06
@whiteleaf

Autoloading Standard recommend

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question