php autoloading

In php, before you can use a class or method inside a file, you have to include the file first.

As it is cumbersome and error-prone to do this manually, you should use autoloading. You have to meet two requirements for this to work best:

  • Use a valid Objective Oriented approach: for example don’t globally define methods, but group similar methods in classes (example: define a public static function convertToInches in the class UnitConverter instead of just defining it globally)
  • Use namespaces: Use namespaces corresponding to the folder structure of your project. Learn about this at PSR-4

The autoloading itself is quite simple and saves you a lot of time. Place the code below at the entry point of your application.

/*** class loader ***/
function load_my_classes($class) {
    // project-specific namespace prefix
    $prefix = 'Vendor\\Project\\';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) === 0) {
		// get the relative class name
                $relative_class = substr($class, $len);
    
		// replace namespace separators with directory separators in the relative class name
		// append .php
		$file = __DIR__ . "/" . str_replace('\\', '/', $relative_class) . '.php';

		// if the file exists, require it
		if (file_exists($file)) {
			require $file;
		} else {    
			throw new Exception("Unable to load class: " . $class . " @ path: " . $file);
		}
	} else {
		//as the class uses an unknown namespace prefix, we ignore this one. An other autoloader can take care of this.
	}
});

/*** register the class loader ***/
spl_autoload_register('spl_autoload_register');

Now, whenever php has to use a class it does not know yet, it calls all methods registered by spl_autoload_register (in our case this is load_my_classes), until the class it included.
If it has called all registered methods, but still the class is not found, your application terminates (obviously).

If you’ve followed the naming conventions as specified in PSR-4, you can even take this a step further with composer. Besides other very useful things, composer does automatically generate the autoloading code. It’s worth giving it a try.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *