Home >Backend Development >PHP Tutorial >mvc-php MVC怎么实现自动加载不同命名空间的类?

mvc-php MVC怎么实现自动加载不同命名空间的类?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-02 11:29:24801browse

phpmvc

我自己想尝试着写个简单的MVC框架,结果在自动加载时就卡住了,求高手指点下
这是目录结构
图片说明
代码如下
入口文件index.php
define('BASEDIR',__DIR__);
require BASEDIR.'\autoload.php';
spl_autoload_register('controllers\Loader::autoload');
$c = strtolower($_GET['c']); //控制器名
$a = strtolower($_GET['a']); //方法名
$controller = 'controllers\index\'.$c.'Controller'; //就是这个地方我想直接new,而不需要在前面加命名空间,不知道该怎么实现
//$controller = $c.'Controller';
$obj = new $controller();
$obj->$a();

控制器commonController.class.php:
namespace controllers\common;
class commonController {
/**

  • @param string $templets
  • @param array $var*/public function display($templets,$var){define('BASEDIR',__DIR__);ob_clean();ob_start();extract($var);$templets = str_replace('/','\',$templets);$tmp_file = BASEDIR.'\views\'.$templets.'.html';include_once $tmp_file;echo ob_get_contents();}}

控制器indexController.class.php:
namespace controllers\index;
use controllers\common\commonController;
class indexController extends commonController{
public function index(){
$this->display('index/index',['test'=>'success']);
}
}

​自动加载类autoload.php:
namespace controllers;
class Loader{
static function autoload($className){
$class = BASEDIR.'\'.$className.'.class.php';
$class = str_replace('\','/',$class);
if(file_exists($class)){
include_once $class;
}
}
}
我想在入口文件直接new载入的类,而不需要在前面添加命名空间,该怎么做,求大神指点下

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn