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

标签 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 /
         something.php

Booter.php 包含:(当前仅适用于位于 core 目录中的文件):

class Booter
{
private static $controller_path, $model_path, $class_path;

public static function setDirs($controller_path = 'application/controllers', $model_path = 'application/models', $classes_path = 'core')
{
    self::$controller_path = $controller_path;
    self::$model_path      = $model_path;
    self::$class_path      = $classes_path;

    spl_autoload_register(array('Booter', 'LoadClass'));
    if ( DEBUG ) 
        Debugger::log('Setting dirs...');
}

protected static function LoadClass($className) 
{
    $className = strtolower($className);

    if ( file_exists(DIR . '/' . self::$model_path . '/' . $className . '.php') ) 
    {
        require(DIR . '/' . self::$model_path . '/' . $className . '.php');
    }       
    else if ( file_exists(DIR . '/' . self::$class_path . '/' . $className . '.class.php') ) 
    {
        require(DIR . '/' . self::$class_path . '/' . $className . '.class.php');
    }
    else if ( file_exists(DIR . '/' . self::$controller_path . '/' . $className . '.php') )
    {
        require(DIR . '/' . self::$controller_path . '/' . $className . '.php');
    }

    if ( DEBUG )
        Debugger::log('AutoLoading classname: '.$className);
}
}

我的应用程序/ Controller /索引 Controller 如下所示:

<?
class IndexController extends Controller
{
     public function ActionIndex()
     {
          $a = new Model; // It works
          $a = new Controller; //It works too
     }
}

?>

这是我的问题:

[问题1]

我的代码目前的工作方式如下:

$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]

对类、 Controller 和模型使用单一自动加载是一个好习惯吗?还是我应该使用 3 种不同的方法定义 3 个不同的 spl_autoload_register?为什么?

最佳答案

我通常在应用程序根目录的 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);

您可以将其推广到您的“Booter”类中,并将目录附加到包含路径中。如果您有明确定义的命名空间名称,则不会出现冲突问题。

编辑: 如果您遵循PSR-1,则此操作有效.

关于PHP:使用命名空间自动加载多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681503/

相关文章:

php - 在 PHP 7.1.6 中使用 MongoDB\Driver 检查 mongodb 中是否存在集合

java - 如何根据对象 instanceof 选择要执行的操作?

ios - 调用 Web 服务方法是 MVC 模式中模型或 Controller 的一部分

c# - 遍历 MultiSelectList

php - 当php中的数组为空时,json_encode函数不返回大括号{}

php - 如果时间戳范围在时间戳范围内

javascript - 简单的 javascript 调用失败

c# - 限制访问类库中的方法和属性

javascript - 将 .apply() 与 'new' 运算符一起使用。这可能吗?

model-view-controller - MVC 系统如何工作?