Howto make your live easier with an autoloader

Do you honestly want to include all needed classes at the top of every one of your php files? If you say yes, go on, have fun with your code, your problem.

Ok, so an autoloader cares about loading all classes needed in your php code. You do not need to  explicitly include them on top of every file, but if you call new myclass, the autoloader takes care about finding the class file. With spl_autoload_register PHP gives you the possibility to register a whole stack of autoloaders. So for example you start with your own autoloader then you might have an external library that needs another autoloader etc.

Example: Project with the following structure:

project structure

project structure

Folder hr is for the projects’s own classes that should lie outside of doc root. Folder hrtest contains the tests for classes in folder hr. Library is for storing external libraries like here  Zend Framework and phpunit.

When using an autoloader, you need a naming style for classes. For example calling new hr_cache_file makes the autoloader search for hr/cache/file.php and include it if the file can be found.

class naming convention

naming convention and file structure

Here’s the autoloader code:

autoloader structure

autoloader structure


autoloader function in detail

autoloader function in detail

Now include autoload.inc.php in your entry point like index.php and call new classname without thinking about explicitly including files.

Short note: The include path is set on the fly at runtime here as I will use the same vhost for other small test projects as well. I’m too lazy to configure it properly right now.

This entry was posted in howto, PHP, tools and tagged , . Bookmark the permalink.

Comments are closed.