[英]spl autoload ignore class that don't exist
我在php中有一个简单的MVC应用程序,该应用程序将第一个查询字符串映射到控制器名称,将第二个查询字符串映射到动作名称,再将其作为参数。 当自动加载类时,它会使用regex寻找命名约定,这很好,但是不会加载明显存在的类。
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存在于controllers目录中。
尝试这个:
try {
$controller_object = new $controller_name($request, $config);
$controller_object->$action_name();
} catch (Exception $e) {
echo "Class doesn't exist : $controller_name";
}
您的条件调用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;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.