<?php
//实现自动加载
class Psr4autoload
{
//存放不守规矩的命名空间名字和路径
protected $namespaces = array();
public function register()
{
spl_autoload_register(array($this , 'loadClass'));
}
//处理类名字
public function loadClass($className)
{
//echo $className.'<br />'; ///Test\TestController
$pos = strrpos($className , '\\');
$namespace = substr($className , 0 , $pos+1); //Test\
$realClassName = substr($className , $pos+1); //TestController
$this->mapLoad($namespace , $realClassName);
}
//添加命名空间
public function addNamespace($namespace , $path)
{
//我要把他们放到一个数组里面去
//var_dump($namespace,$path);
$this->namespaces[$namespace][] = $path;
var_dump($this->namespaces);
}
//处理包含问题
public function mapLoad($namespace , $realClassName) //Test\ testController
{
//处理两种情况
if (isset($this->namespaces[$namespace]) == false) {
//守规矩的 命名空间名字能跟文件夹对应上
$path = $namespace . $realClassName . '.php';
$path = str_replace('\\' , '/' , $path);
$file = strtolower($path);
$this->requireFile($file);
} else {
//不守规矩
foreach ($this->namespaces[$namespace] as $path) {
//echo $path;
$file = $path . '/' . $realClassName . '.php';
$this->requireFile($file);
}
}
}
//执行包含
public function requireFile($file)
{
if (file_exists($file)) {
include $file;
return true;
}
return false;
}
}
$loader = new Psr4autoload();
$loader->register();
$loader->addNamespace('Controller\\' , 'app/controller');
//不守规矩
$c = new Controller\IndexController();
$c->index();
//守规矩
//$t = new Test\TestController();
//$t->show();