D
D
dev4002016-08-13 20:52:48
PHP
dev400, 2016-08-13 20:52:48

How to use autoload.php from composer?

The project had a class autoloader

class Loader {

    public static function init() {
        spl_autoload_register( [new self, 'autoload'] );
    }

   public function autoload($className)
    {
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';

        if ($lastNsPos = strripos($className, '\\')) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }

        $fileName .= $className . '.php';


        if ( is_readable( $fileName) ) {
            include $fileName;
        }
    }
}

Composer has now appeared, and it also has its own autoload.php. How to be now? Merge them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
novrm, 2016-08-14
@dev400

Taken from Composer Cheat Sheet for developers .
Here's a more extended example:

"autoload": {
        "psr-4": {
            "Application\\": "module/Application/src/",
            "Vendor\\Namespace\\": ""
        },
        "psr-0": {
            "Monolog": "src/",
            "Vendor\\Namespace": ["src/", "lib/"],
            "Pear_Style": "src/",
            "": "src/"
        },
        "classmap": ["src/", "lib/", "Something.php"],
        "files": ["src/MyLibrary/functions.php"]
    },

In addition, in order to update these dependencies when installing new modules, you need to either write in composer.json:
"config": {
        "optimize-autoloader": true
    },

or manually call the command for composer:
$ php composer.phar dump-autoload --optimize

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question