/class-loader

Class loader implementation (PSR-0, PSR-4)

Primary LanguagePHPMIT LicenseMIT

Class loader

PHP class loader that implements both PSR-0 and PSR-4 autoloading.

https://travis-ci.com/kuria/class-loader.svg?branch=master
  • PSR-0 and PSR-4 autoloading
  • class maps
  • custom suffixes
  • composer bridge
  • debug mode
  • PHP 7.1.0+
<?php

use Kuria\ClassLoader\ClassLoader;

// load the class loader manually
require '/path/to/src/ClassLoader.php';

// create an instance
$debug = true; // true during development, false in production

$classLoader = new ClassLoader($debug);

// register the autoloader
$classLoader->register();

// PSR-4 prefix
$classLoader->addPrefix('Foo\\Bar\\', 'vendor/foo/bar/src');

$classLoader->addPrefixes([
    'Kuria\\Error\\' => 'vendor/kuria/error/src',
    'Foo\\Baz\\' => 'example/foo/baz',
]);

// PSR-0 prefix
$classLoader->addPrefix('Example\\FooBar\\', 'vendor/example/foobar', ClassLoader::PSR0);

$classLoader->addPrefixes([
    'Kuria\\Error\\' => 'vendor/kuria/error/src',
    'Foo_' => 'example/foo',
], ClassLoader::PSR0);

// PSR-4 fallback (empty prefix)
$classLoader->addPrefix('', 'src');

// PSR-0 fallback (empty prefix)
$classLoader->addPrefix('', 'old-code/example', ClassLoader::PSR0);

// single class
$classLoader->addClass('Foo', 'path/to/foo.class.php');

// class map
$classLoader->addClassMap([
    'Bar' => 'path/to/bar.class.php',
    'Baz' => 'path/to/baz.class.php',
]);

The ComposerBridge class can be used to initialize autoloading for packages managed by Composer.

<?php

use Kuria\ClassLoader\ClassLoader;
use Kuria\ClassLoader\ComposerBridge;

require __DIR__ . '/vendor/kuria/class-loader/src/ClassLoader.php';
require __DIR__ . '/vendor/kuria/class-loader/src/ComposerBridge.php';

$classLoader = new ClassLoader();

ComposerBridge::configure($classLoader, __DIR__ . '/vendor');

$classLoader->register();

If you are using an optimized autoloader, you can pass an optional third parameter to configure() to disable prefixes completely. Only the class maps and files will be loaded.

<?php

ComposerBridge::configure($classLoader, __DIR__ . '/vendor', false);

If debug mode is enabled, a check is performed after a file has been loaded to determine whether the class, interface or trait was defined in that file.

This helps detect wrong or misspelled namespaces or class names.

To enable debug mode, call $classLoader->setDebug(true) or pass true to the appropriate constructor argument.