PHP mvc自动加载器没有加载类/函数

时间:2016-04-19 13:22:19

标签: php model-view-controller autoloader

我不知道为什么我的自动加载器类无法正常工作。
我收到以下错误: 致命错误:Class' files \ testmodel'在第10行的D:\ wamp \ www \ Opdrachten \ MVC-eindopdracht \ app \ controllers \ content.php中找不到

Autoloader类: 在app / core / autoloader.php

class Autoloader
    {
    protected $directories = array();

private function loadClass($class)
{
    if ($class[0] == '\\')
    {
        $class = substr($class, 1);
    }

    $class = str_replace(array('\\', '_'), '/', $class). '.php';

    foreach ($this->directories as $directory)
    {
        if (file_exists($path = $class))
        {
            require_once $path;
            echo $path;
            return true;
        }
    }
}

public function register()
{
    spl_autoload_extensions('php');
    spl_autoload_register(array($this, 'loadClass'));
}

public function addDirectories($directories)
{
    $this->directories = (array) $directories;
}

}

我的Index.php

use app\core as core;
use app\lib as lib;


include('./app/core/autoloader.php');

$autoloader = new Autoloader();
$autoloader->addDirectories(
    array(
        'lib',
        'controllers',
        'core',
        'models'
        ));


$autoloader->register();

$route = new core\Router();
$route->route();

我的测试类 app / models / files / testmodal.php

namespace files;
class testmodel
{
    public function $user;
    public function test()
    {
        $user = 'pieter';
        return $user;
    }
}
app / controllers / content.php中的

内容类:

class content
{
    public $title;
    public $data;

    public function __construct()
    {
        $this->_model = new files\testmodel();
    }

    public function home()
    {
        $this->title = "Home";
        $this->data = array('test', 'test123', 'test456');

        $user = $this->_model->test();
        $this->user = $user;

    }
}

1 个答案:

答案 0 :(得分:0)

我使用以下代码修复了它:

class autoloader
{
    protected $directories = array();

    private function loadClass($class)
    {
        if($class[0] == '\\')
        {
            $class = substr($class, 1);
        }
        $class = str_replace(array('\\','_'), '/', $class).'.php';

        foreach($this->directories as $directory)
        {
            if(file_exists($path = $directory.'/'.$class))
            {
                require_once $path; 
                return true;                
            }
        }
    }

    public function register()
    {
        spl_autoload_extensions('php');
        spl_autoload_register(array($this,'loadClass'));

    }
    public function addDirectories($directories){
        $this->directories = (array) $directories;

    }
}