【问题标题】:spl autoload ignore class that don't existspl 自动加载忽略不存在的类
【发布时间】:2015-02-13 11:22:07
【问题描述】:

我在 php 中有一个简单的 MVC 应用程序,它将第一个查询字符串映射到控制器名称,第二个映射到操作以及更多作为参数。自动加载类时,它会使用正则表达式查找命名约定,这很好,但它不会加载明显存在的类。

spl_autoload_register(function ($class) {
    if (preg_match('/[a-zA-Z]+Controller$/', $classname)) {
        if (class_exists(__DIR__ . '/controllers/' . $classname)) {
            //never gets to here, even though the file gets
            //included by the require statement below
        }
    require __DIR__ . '/controllers/' . $classname . '.php';
    return true;
}
});

//controller and action are "default" and "index" by default
//If a query string is passed, it gets the parts
$controller = $url[0];
$action = $url[1];

$controller_name = ucfirst($controller) . "Controller";
$action_name = $action . "Action";

if (class_exists($controller_name)) {
    $controller_object = new $controller_name($request, $config);
    $controller_object->$action_name();
} else {
    echo "Class doesn't exist : $controller_name";
}

示例输出:

url.com/ = 类不存在“DefaultController”

url.com/default = 类不存在“DefaultController”

url.com/test = 类不存在“TestController”

DefaultController 存在于控制器目录中。

【问题讨论】:

  • 我很确定 spl 自动加载仅在您实际尝试创建新类对象时自动加载。
  • class_exists(__DIR__ . '/controllers/' . $classname) => 你的意思是file_exists__DIR__ . '/controllers/' . $classname

标签: php spl spl-autoload-register


【解决方案1】:

您的条件调用class_exists() 函数,您的意思是检查文件:

spl_autoload_register(function ($class) {
    if (preg_match('/[a-zA-Z]+Controller$/', $classname)) {
        if (file_exists(__DIR__ . '/controllers/' . $classname)) {
            require __DIR__ . '/controllers/' . $classname . '.php';
            return true;
        }
}
});

【讨论】:

    【解决方案2】:

    试试这个:

    try {
      $controller_object = new $controller_name($request, $config);  
      $controller_object->$action_name();
    } catch (Exception $e) {
        echo "Class doesn't exist : $controller_name";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2010-12-15
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多