Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add case insensitive autoloading using composer generated classmap?

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?

like image 595
sectus Avatar asked Nov 27 '13 07:11

sectus


3 Answers

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.

like image 143
sectus Avatar answered Oct 16 '22 20:10

sectus


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.

like image 32
Sven Avatar answered Oct 16 '22 21:10

Sven


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();
like image 2
Ruslan Zaytsev Avatar answered Oct 16 '22 21:10

Ruslan Zaytsev