WordPress Autoloader makes WordPress developers life really easy. This plugin loads automatically any PHP class. Many WordPress developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class). With WordPress Autoloader, this is no longer necessary.
The great advantage of automatically loaded classes is also perfomance increase, wich means faster loading. Loading unneeded files wastes server resources and increases webpage load time.
How it works?
If you put all your classes into /lib folder on your theme or plugin root directory, then all these classes are loaded automatically only when actually needed. Additionally you can define class search path or your own method to automatically load your classes in case you are trying to use a class/interface which hasn't been defined yet. By using WordPress Autoloader the scripting engine is given a last chance to load the class before PHP fails with an error.
You have several options to get your classes loaded automatically. The best option is to use the /lib subfolder on you plugin or theme root path, just put all files inside this direcotry and all classess are loaded automatically. The second and easiest way is to define search path for your classes. For advanced needs, the second option is to create your own __autoload method and register it.
Easiest way to get your classes loaded automatically is to put all classes into /lib path under your plugin/theme root folder:
/lib /MyClassA.php /MyNameSpace /MyClassB.php /MyClassC.php
On case above, classes MyClassA, MyNameSpace\MyClassB and MyNameSpace\MyClassC are loaded automatically and you don't have to worry about registering classes search path.
Register search path
If your classes library is not located inside /lib, you can register search paths for your classes.
wp_autoload_register_path ( realpath ( './my_library_path' ) );
This example uses init.php file which should be placed in your classes root directory, to get valid path to the library. Add code below into init.php and request once init.php file from your theme functions.php or from <custom-plugin>.php file.
wp_autoload_register_path ( __FILE__ );
Register your own function
This option is useful, if your libary file tree strucutre does not support your classes namespaces structure. For first you have to create your own method to handle __autoload request. For second you have to register your custom method by using method wp_autoload_register_function.
bool wp_autoload_register_function ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
wp_autoload_register_function ( 'MyClass::MyStaticFunction' ); wp_autoload_register_function ( array( 'MyClass', 'MyStaticFunction' ) ); wp_autoload_register_function ( 'MyAutoLoadFuncton' );