2016-04-19 15 views
0

Ich weiß nicht, warum meine Autoloader-Klasse nicht funktioniert.
bekomme ich folgende Fehlermeldung: Fatal error: Class 'files \ testmodel' nicht in D gefunden: \ wamp \ www \ opdrachten \ MVC-eindopdracht \ app \ Controller \ content.php on line 10PHP mvc autoloader nicht laden Klassen/Funktionen

Autoloader-Klasse: In app/Kern/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; 
} 

} 

Mein 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(); 

Meine Testklasse app/models/files/testmodal.php

namespace files; 
class testmodel 
{ 
    public function $user; 
    public function test() 
    { 
     $user = 'pieter'; 
     return $user; 
    } 
} 

Inhalt Klasse: in 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; 

    } 
} 
+0

Sie tun 'if (file_exists ($ path = $ class))'. Bist du sicher, dass das korrekt ist? – Valdars

Antwort

0

Ich reparierte Verwenden Sie dazu den folgenden Code:

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; 

    } 
}