Are there best practices for organizing classes in different directories and loading them using autoloaders in PHP?

When organizing classes in different directories and using autoloaders in PHP, it is best practice to follow PSR-4 standards for autoloading classes. This involves mapping namespaces to directory structures, making it easier to autoload classes without the need for manual inclusion. By defining an autoloader function that follows the PSR-4 standard, classes can be autoloaded dynamically based on their namespace and directory structure.

spl_autoload_register(function($class) {
    // project-specific namespace prefix
    $prefix = 'MyNamespace\\';

    // 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
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

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