How to add case insensitive autoloading using composer generated classmap?

99封情书 提交于 2021-02-04 17:55:28

问题


I have legacy project which has declartions and class usings in different cases.

I want upgrade source to modern state. First I want to replace legacy autoloading by composer autoloading. But composer does not provide case insensitive autoloading.

How to use composer classmap and insensitive autoload?


回答1:


Add classmap to composer.json.

"autoload": {
    "classmap": ["folder1/", "folder2/"]
},

Then run composer.phar dumpautoload to create composer/autoload_classmap.php.

Change your code. After

require VENDOR_PATH . '/autoload.php';

Add

$class_map = require VENDOR_PATH . '/composer/autoload_classmap.php';
$new_class_map = array();
foreach ($class_map as $class => $file)
    $new_class_map [strtolower($class)] = $file;
unset($class_map);
spl_autoload_register(function ($class)use($new_class_map)
        {
        $class = strtolower($class);
        if (isset($new_class_map[$class]))
            {
            require_once $new_class_map[$class];
            return true;
            }
        else
            return false;
        }, true, false);
unset($new_class_map);

This is the simplest way I have found.




回答2:


You don't - with composer.

Fix the code. I.e. use Composer to create a classmap of your classes, then make a case insensitive search for all these class names, and replace them with the correct case sensitive version from the classmap.

Or create your own case-insensitive classmap loader that automatically complains if it stumples upon a classname with incorrect cases and makes you fix the software one by one - with the danger of missing some cases that will only be detected later if code changes rearrange the order of autoloaded classes.




回答3:


If your production setup supports spl_autoload_register (starting from 5.1.2) - you can add own implementation of autoload alongside with composer's. Here how mine is done (it also relies on name spacing):

autoload.php

<?php
spl_autoload_register('classLoader');

function classLoader($className, $prefix = '') {
  $pathParts = explode('\\', $className);
  $newPathParts = array_map('strtolower', $pathParts);
  $classPath = $prefix . implode(DIRECTORY_SEPARATOR, $newPathParts) . '.php';

  if ( file_exists($classPath) ) {
    require_once $classPath;
  }
}

?>

And in your files you can mix your case whatever you like.

$obj = new View\Home\Home();

is identical to:

$obj = new vIEw\home\homE();


来源:https://stackoverflow.com/questions/20235922/how-to-add-case-insensitive-autoloading-using-composer-generated-classmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!