Php – How should I design a PHP class autoloader

designPHP

I have a fairly simple folder structure where the main classes are in a folder, and any classes used by those classes are in a subfolder with the same name as that class.

/exampleClass.php
/exampleClass/usedByExampleClass.php

I am trying to come up with a simple autoloader for this naming convention.

So far, my idea is to use underscores in the class name wherever there might be a forward slash in the class path. This way I can simply replace all underscores with forward slashes in the autoloader, and load the class file.

This means that the class name found in file:

/exampleClass/usedByExampleClass.php

would be:

exampleClass_usedByExampleClass

These class names end up being very long however, and I would like to shorten them while still having a simple autoloader for this folder structure.

Any ideas or thoughts on how to achieve both short class names and a simple autoloader for this folder structure?

Best Answer

How should I design a PHP class autoloader?

You shouldn't.

Leads from a number of PHP frameworks (Zend Framework, CakePHP, etc) and applications (Joomla, phpBB, etc) came together in late 2009 to build the PSR-0 Autoloader Proposal, which dictates a class file naming scheme and namespace mechanism.

It's remarkably similar to your existing system, with the simple inclusion of PHP 5.3 namespaces.

It's simple, it's straightforward, and if all goes well, it'll Just Work(tm) with a large body of third party code in the future.