Automatic class loading and naming conventions with Symfony2, PHPUnit and PHP 5.3
I mentioned yesterday that I am toying around with some little library code that is completely standalone.
As I plan on using this code in a Symfony2 project later I chose to finally switch to PHP 5.3 including namespaces.
And as soon as I started I needed to decide on a naming convention for my classes, a directory structure, a convention to name my PHPUnit tests and a way to autoload these classes to avoid require statements.
Of course I don’t fancy to come up with all that on my own. In fact I’d rather prefer to use existing conventions and luckily I found one that is used in Symfony2 but was in fact created by a group of PHP developers worldwide from all kinds of projects including the Zend Framework. This group of people is called the PHP Standards Working Group and they agreed on a paper called PSR-0 Final Proposal.
Everything defined in there pretty much reminds me of the Zend Framework conventions only much much simpler as namespaces are a very efficient way to organise code.
So I went and created a simple dummy library with the following:
- Two stupid classes with one method each
- Two PHPUnit tests
- All namespaces set up just like in Symfony2 for library code as well as unit tests
- A demonstration of a namespace type hint
- A PHPUnit configuration file for distribution
- A bootstrap file initialising the Symfony2 universal class loader
I think for those of you interested it will be far more convenient to take a look on GitHub or clone the sources instead of me writing down snippets of code. So here you can find my example code on GitHub.
You can see it’s dead simple. Even the autoloading is nicely tucked up.
Tell me what you think!