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
>重命名我的文件(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.)

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...