Search code examples
phpnamespacesautoloadautoloaderpsr-0

PSR-0 autoloader: Namespaces and the directory structure


Does the PSR-0 autoloader convention require using namespaces that map to the directory structure?

function autoload($className)
{
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

    require $fileName;
}

Solution

  • PSR-0 require it.

    Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.

    and

    The fully-qualified namespace and class is suffixed with .php when loading from the file system.

    https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md