PHP:使用名称空间自动加载多个类

PHP:使用名称空间自动加载多个类,php,oop,model-view-controller,namespaces,autoload,Php,Oop,Model View Controller,Namespaces,Autoload,我正在尝试构建自己的内部使用框架。 我的结构是这样的: index.php boot / booter.php application / controllers / indexcontroller.php core / template.class.php model.class.php controller.class.php cache / memcached.php something /

我正在尝试构建自己的内部使用框架。 我的结构是这样的:

index.php
boot /
    booter.php
application /
     controllers /
           indexcontroller.php
core /
    template.class.php
    model.class.php
    controller.class.php
    cache / 
         memcached.php
    something /
         something.php
<?
class IndexController extends Controller
{
     public function ActionIndex()
     {
          $a = new Model; // It works
          $a = new Controller; //It works too
     }
}

?>
$a = new Model; // Class Model gets included from core/model.class.php
php包含:(它当前只处理位于核心目录中的文件):

我的应用程序/控制器/indexcontroller如下所示:

index.php
boot /
    booter.php
application /
     controllers /
           indexcontroller.php
core /
    template.class.php
    model.class.php
    controller.class.php
    cache / 
         memcached.php
    something /
         something.php
<?
class IndexController extends Controller
{
     public function ActionIndex()
     {
          $a = new Model; // It works
          $a = new Controller; //It works too
     }
}

?>
$a = new Model; // Class Model gets included from core/model.class.php
我如何通过使用名称空间的类实现包含文件?例如:

$a = new Cache\Memcached; // I would like to include file from /core/CACHE/Memcached.php
$a = new AnotherNS\smth; // i would like to include file from /core/AnotherNS/smth.php 
等等。如何生成名称空间的处理

[问题2]

对类、控制器和模型使用单一自动加载是一种好的做法,还是我应该用3种不同的方法定义3种不同的spl\u自动加载\u寄存器,以及为什么?

问题1:

在自动加载器中,将\(用于名称空间)更改为
目录\分隔符
。这应该起作用:

protected static function LoadClass($className) 
{
    $className = strtolower($className);
    $className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
...
}
始终使用
目录\u分隔符
,尤其是如果该软件有可能在其他平台上使用

问题2:


我会使用一个名称空间来分隔类。然而,我认为这取决于您希望如何构造框架以及如何分离代码。其他人可能能够更好地回答这个问题。

我通常在应用程序根目录中的文件夹
conf
中有一个
bootstrap.php
文件。我的代码通常位于
src
文件夹中,也位于根目录中,因此,这对我来说很好:

<?php

define('APP_ROOT', dirname(__DIR__) . DIRECTORY_SEPARATOR);

set_include_path(
    implode(PATH_SEPARATOR,
        array_unique(
            array_merge(
                array(
                    APP_ROOT . 'src', 
                    APP_ROOT . 'test'
                ),
                explode(PATH_SEPARATOR, get_include_path())
            )
        )
    )
);

spl_autoload_register(function ($class) {
    $file = sprintf("%s.php", str_replace('\\', DIRECTORY_SEPARATOR, $class));
    if (($classPath = stream_resolve_include_path($file)) != false) {
        require $classPath;
    }
}, true);