Autoload classes from different folders

Autoload classes from different folders

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Autoload classes from different folders

You're facing a classic architectural decision: how to map namespace-less class names to physical files across multiple directories without duplicating logic or violating naming conventions. Your current setup uses a __autoload callback that constructs a filename by lowercasing the class name, prepending class_, and appending .php. This works for your controllers in AP_SITE.controllers/, but you need to extend this to handle models in a separate folder with a different prefix (model_ instead of controller_base or just implicit mapping).

Simply duplicating the autoload logic with a second function targeting models/ is technically feasible but introduces maintenance debt. Every time you add a new directory—say, for repositories, services, or helpers—you'd need another conditional block inside your autoload hook. This quickly becomes fragile and hard to read. A cleaner approach leverages the predictable structure of your existing naming conventions.

In your case, controllers use controller_ prefix in filenames while models use model_. Both follow a consistent pattern: the class name (in lowercase with underscores) maps directly to a file path under a specific directory with a known prefix. Instead of branching logic inside __autoload, you can normalize the resolution process by inspecting the class name prefix and directing it to the appropriate folder dynamically.

Here’s how you might refactor your autoload function:

function __autoload($class_name) {
    // Normalize class name to lowercase with underscores if needed
    $normalized = strtolower(str_replace('_', '_', $class_name)); // redundant but safe
    
    // Determine prefix and path based on common naming patterns
    if ($normalized === 'controller_' . lcfirst(substr($normalized, 10))) {
        $prefix = 'controller_';
        $dir = AP_SITE . '/controllers/';
    } elseif ($normalized === 'model_' . lcfirst(substr($normalized, 6))) {
        $prefix = 'model_';
        $dir = AP_SITE . '/models/';
    } else {
        // Fallback or error handling for unknown classes
        return false;
    }

    $filename = $prefix . substr($normalized, strlen($prefix)) . '.php';
    $file = $dir . $filename;

    if (file_exists($file) === false) {
        return false;
    }

    include $file;
}

This approach centralizes the dispatch logic, making it easier to extend later without bloating each directory's rules. However, be cautious: this relies heavily on your naming conventions staying consistent. If a model is named model_user but stored as class_model_user.php, the prefix check breaks. Always validate that your file system matches your class declarations before trusting dynamic resolution.

Another consideration is performance. Your current method checks file_exists() every time a class is autoloaded. For high-traffic applications, this I/O operation can add measurable latency. If you’re building a long-term framework, consider caching resolved paths in memory using a simple static array keyed by class name. But for most projects, especially those still using PHP 5-style autoloading (which is deprecated as of PHP 7.3), the overhead is negligible.

Remember that __autoload was removed in PHP 7.2+ and replaced with spl_autoload_register. If you're starting a new project or upgrading your stack, migrating to PSR-4 autoloaders will eliminate these manual path calculations entirely. You’ll define namespaces like App\Controllers and map them directly to controllers/, removing the need for custom filename mangling altogether.

For now, though, this pattern gives you a scalable way to handle multiple directories without code duplication or rigid if-else chains. Just keep your file naming disciplined, and your autoload resolver will stay clean and maintainable.

Our network