加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 15:56:29 所属栏目: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/controlle
我见过这些,

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

示例代码,

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;
}

输出是

Customer -> /models/customer.php

CustomerController -> /controllers/customer.controller.php

您现在需要在自动加载器功能中使用makeFileName.

我自己强烈反对这样的事情.我会使用反映命名空间和类名的命名空间和文件名.我也用Composer.

(我发现了splitCamelCase here.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读