1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
<?php
class Loader{
protected static $_directory;
private static $_erreurs;
public function register($name,$dir,$ext='php'){
if(isset($this->directory->$name)){self::messageErreur("Name $name already exist in Loader::directory"); return;}
$this->directory->$name->root = $dir;
$this->directory->$name->extention = $ext;
self::$_directory = $this ;
spl_autoload_register(array($this,'__autoload'),true);
return $this->directory->$name;
}
public function unregister($name){
unset($this->directory->$name);
return $this;
}
private function __call($class,$null=null)
{
try{
$erreur = true;
foreach ($this->directory as $property ) {
$ext = $property->extention;
$path = self::getPath($class);
$file = $property->root.$path.'/'.$class.'.'.$ext;
if(file_exists($file)){
require_once $file;
$erreur = false;
}
}
if($erreur){throw new Exception("File $class not found , in Loader::directory ");}
}
catch (Exception $e) {
self::messageErreur($e);
}
}
public static function directory(){
return self::$_directory;
}
public function autoload($path,$options=null){
$pathTab=explode('::',$path);
$class = $pathTab[0] ;
$method =isset($pathTab[1]) ? $pathTab[1] : null;
$this->__call($class);
try{
if(!null == $class && !null == $method && class_exists($class) && method_exists($class,$method)){
$class = new $class;
$class->$method($options);
}else{
throw new Exception("Class $class or method $method no found , call file path : $path ");
}
}
catch (Exception $e) {
self::messageErreur($e);
}
}
private static function getPath($path){
return str_replace('_','/',$path);
}
public static function messageErreur($msg = ''){
self::$_erreurs[] = $msg ;
if (!defined('SHOW_MESSAGE_ERREUR') || SHOW_MESSAGE_ERREUR == 'SHOW_MESSAGE_ERREUR' || SHOW_MESSAGE_ERREUR === true ){
try {
throw new Exception($msg);
}
catch (Exception $e) {
echo "Message : ", $e->getMessage(), "\n\r<br/><br/>";
}
}
}
}
/*
par exemple créer un repertoire dans /library/class/View/View.php
Class View{
public function accueil($string){
echo $string;
}
}
*/
define('__DIR__' , dirname(__FILE__));
$loader = new Loader;
$loader->register('library',__DIR__.'/library/class/' ,'php');
$loader->register('public' ,__DIR__.'/public/' ,'php');
$loader->register('route' ,__DIR__.'/' ,'php');
print_r(Loader:: directory());
echo "<br/><br/>";
$loader->register('public',__DIR__.'/library/' ,'php');
$loader->autoload('View::accueil',"c'est un test");
$loader->autoload('View::test',"c'est un test");
$view = new View;
?> |
Partager