PSR-4-autoloader-examples

다음 예는 PSR-4에 호환하는 코드입니다.

역자주: 사실상 오토로더는 컴포저로 대동단결 되었기 때문에 직접 구현하시기 보다는 컴포저를 사용하시는 것을 추천합니다

Closure 예제

<?php
/**
 * An example of a project-specific implementation.
 *
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 *
 *      new \Foo\Bar\Baz\Qux;
 *
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'Foo\\Bar\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

Class 예제

다음은 네임스페이스를 활용하여 여러 클래스를 처리하기위한 클래스 구현의 예제입니다.

Unit Tests

다음 예제는 위의 클래스 로더를 단위 테스트하는 방법의 한 가지입니다.

Last updated

Was this helpful?