php – 如何自动加载文件名与类名不同的类?
|
我见过这些,
How to autoload class with a different filename? PHP Load a class with a different name than the one passed to the autoloader as argument 我可以改变但是在我的MV *结构中我有: /models
customer.class.php
order.class.php
/controllers
customer.controller.php
order.controller.php
/views
...
在它们的实际课程中, class CustomerController {}
class OrderController{}
class CustomerModel{}
class OrderModel{}
我试图与这些名字保持一致.如果我没有把类名后缀(Controller,Model),我无法加载该类,因为这是重新声明的. 如果我保留我的类的名称,自动加载会失败,因为它将查找名为的类文件 CustomerController 当文件名确实是, customer.controller.php 是我唯一的方式(无序): >使用create_alias ? 示例代码, function model_autoloader($class) {
include MODEL_PATH . $class . '.model.php';
}
spl_autoload_register('model_autoloader');
好像我要重命名文件, http://www.php-fig.org/psr/psr-4/ “终止类名对应于以.php结尾的文件名.文件名必须与终止类名的大小写相匹配.” 解决方法
在我看来,这可以通过一些基本的字符串操作和一些约定来处理.
define('CLASS_PATH_ROOT','/');
function splitCamelCase($str) {
return preg_split('/(?<=w)(?=[A-Z])/',$str);
}
function makeFileName($segments) {
if(count($segments) === 1) { // a "model"
return CLASS_PATH_ROOT . 'models/' . strtolower($segments[0]) . '.php';
}
// else get type/folder name from last segment
$type = strtolower(array_pop($segments));
if($type === 'controller') {
$folderName = 'controllers';
}
else {
$folderName = $type;
}
$fileName = strtolower(join($segments,'.'));
return CLASS_PATH_ROOT . $folderName . '/' . $fileName . '.' . $type . '.php';
}
$classNames = array('Customer','CustomerController');
foreach($classNames as $className) {
$parts = splitCamelCase($className);
$fileName = makeFileName($parts);
echo $className . ' -> '. $fileName . PHP_EOL;
}
输出是
您现在需要在自动加载器功能中使用makeFileName. 我自己强烈反对这样的事情.我会使用反映命名空间和类名的命名空间和文件名.我也用Composer. (我发现了splitCamelCase here.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
