Autoload classes from different folders

Hi,

This is how I autoload all the classes in my controllers folder,

# auto load controller classes
    	function __autoload($class_name) 
    	{
    		$filename = 'class_'.strtolower($class_name).'.php';
    		$file = AP_SITE.'controllers/'.$filename;
    
    		if (file_exists($file) == false)
    		{
    			return false;
    		}
    		include ($file);
    	}

But I have classes in models folder as well and I want to autoload them too - what should I do? Should I duplicate the autoload above and just change the path to models/ (but isn’t this repetitive??)?

These are my classes file names in the controller folder:

 
class_controller_base.php
class_controller_factory.php
etc

these are my classes file names in the model folder:


class_model_page.php
class_model_parent.php
etc

this is how I name my controller classes class usually (I use underscores and lowcaps),


class controller_base 
    {
    ...
    }
    
class controller_factory
    {
    ...
    }

this is how I name my model classes class usually (I use underscores and lowcaps),

 
class model_page 
        {
        ...
        }
        
class model_parent
        {
        ...
        }

Thanks.

If you keep with the naming conventions and directory structure you’ve established, then you could simply take the class name, chop off the part from the first underscore on, add an ‘s’, and that becomes the directory to look in.

If you see that pattern changing in the future, it might be a good time to consider new naming conventions

Thanks. Here is my solution,

class autoloader
	{
		private $directory_name;
		
		public function __construct($directory_name)
		{
			$this->directory_name = $directory_name;
		}
	
		public function autoload($class_name) 
		{ 
			$file_name = 'class_'.strtolower($class_name).'.php';
			
			$file = AP_SITE.$this->directory_name.'/'.$file_name;

			if (file_exists($file) == false)
			{
				return false;
			}
			include ($file);
		}
	}
	$controllers_loader = new autoloader('controllers');
        $models_loader = new autoloader('models');
	spl_autoload_register(array($controllers_loader, 'autoload'));
        spl_autoload_register(array($models_loader, 'autoload'));


But I am not sure… what do you think?

Thanks.