php – 如何自动加载文件名与类名不同的类?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 如何自动加载文件名与类名不同的类?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我见过这些,

How to autoload class with a different filename? PHP

@L_512_1@

我可以改变但是在我的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
>重命名我的文件(customer.model.PHP到customermodel.PHP)
>重命名我的课程
>使用正则表达式
>使用包含文件引导程序(包括,
require_once等)

示例代码,

function model_autoloader($class) {
    include MODEL_PATH . $class . '.model.PHP';
}

@R_304_4@('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.)

脚本宝典总结

以上是脚本宝典为你收集整理的php – 如何自动加载文件名与类名不同的类?全部内容,希望文章能够帮你解决php – 如何自动加载文件名与类名不同的类?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。