我的MVC结构如下:
- web
-- Classes
--- Loader.php
-- Core
--- Controller.php
--- Model.php
--- View.php
--- Bootstrap.php
--- DB.php
-- Project
--- Controllers (folder)
--- Models (folder)
--- Views (folder)
现在,我为每个名称空间指定了名称空间。例如,我有
namespace Classes; //for Loader.php
namespace Core; //For Controller.php, Model.php etc...
namespace ProjectControllers; //For Controllers inside Controllers folder etc...
我的自动加载器看起来像这样:
public static function Autoloader2($className) {
$className = explode('\', $className);
$class = array_pop($className);
$namespace = implode(DIRECTORY_SEPARATOR, $className);
$file = $namespace . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
require $file;
}
My main index.php使用
spl_autoload_register( array('Loader', 'Autoloader2') );
$app = new CoreBootstrap();
当我打开localhost/web时/我得到以下错误:
Warning: require(Core/Project/Controllers/Index.php): failed to open stream: N
它似乎为请求的文件准备了Core/。Index.php位于Project/Controllers内部,而不是核心/Project/Controller。如果我试图删除
//namespace Core; from Bootstrap.php i get the following error
Fatal error: Class 'CoreBootstrap' not found
请帮助
您应该使用$app = CoreBootstrap();
。
路径前面的斜杠很重要,如果没有它,命名空间路径将是相对的。