Autoloader ========== * [Home](help) There is some initial support to class autoloading in Friendica core. The autoloader code is in `include/autoloader.php`. It's derived from composer autoloader code. Namespaces and Classes are mapped to folders and files in `library/`, and the map must be updated by hand, because we don't use composer yet. The mapping is defined by files in `include/autoloader/` folder. Currently, only HTMLPurifier library is loaded using autoloader. ## A quick introdution to class autoloading The autoloader it's a way for php to automagically include the file that define a class when the class is first used, without the need to use "require_once" every time. Once is setup you don't have to use it in any way. You need a class? you use the class. At his basic is a function passed to the "spl_autoload_register()" function, which receive as argument the class name the script want and is it job to include the correct php file where that class is defined. The best source for documentation is [php site](http://php.net/manual/en/language.oop5.autoload.php). One example, based on fictional friendica code. Let's say you have a php file in "include/" that define a very useful class: ``` file: include/ItemsManager.php array($baseDir."/include"); ); ``` That tells the autoloader code to look for files that defines classes in "Friendica" namespace under "include/" folder. (And btw, that's why the file has the same name as the class it defines.) *note*: The structure of files in "include/autoloader/" has been copied from the code generated by composer, to ease the work of enable autoloader for external libraries under "library/" Let's say now that you need to load some items in a view, maybe in a fictional "mod/network.php". Somewere at the start of the scripts, the autoloader was initialized. In Friendica is done at the top of "boot.php", with "require_once('include/autoloader.php');". The code will be something like: ``` file: mod/network.php getAll(); // pass $items to template // return result } ``` That's a quite simple example, but look: no "require()"! You need to use a class, you use the class and you don't need to do anything more. Going further: now we have a bunch of "*Manager" classes that cause some code duplication, let's define a BaseManager class, where to move all code in common between all managers: ``` file: include/BaseManager.php