Efficient autoloaders for PHP
Class autoloading is one of more commonly used features in PHP 5. It simplifies the application development, freeing us from manual dependency management. On the other hand, many projects developed custom class naming standards and autoloaders that were incompatible one with another. Currently more and more programmers notice the benefits that come from accepting a single, widely implemented convention. In this article we are going to introduce Open Power Autoloader, a collection of universal, fast autoloaders for PHP 5.3 compatible with PSR-0 class naming convention adapted by such projects, as Zend Framework or Symfony 2.
Table of Contents
Many programmers tend to invent custom, project-specific class naming systems that are not used anywhere else, which forces them to write a custom autoloader for them as well. This approach causes lots of problems, when we try to link several pieces of code and libraries into a single system. The only way is to register all the autoloaders and hope that they will not collide one with another. The community noticed the problem after releasing PHP 5.3 which introduced the concept of namespaces. It was obvious that unless we want a complete chaos, some basic common conventions must be defined and widely accepted. Such a convention, called PSR-0 has been finally defined, and implemented in a group of the biggest PHP projects, such as Doctrine 2, Symfony 2 and Zend Framework. It also allowed to create the first universal autoloaders, capable of handling any number of libraries in a single instance.
Class autoloaders have a critical impact on the application performance. In modern web applications, the number of classes loaded in a single request can exceed 100. For each of them, the autoloading function must be called which translates the class name to a file path and attempts to load it. Here is an example. A couple of months ago I was developing a web application with PHP 5.3. One day I started profiling the code and I was surprised with the first results. It turned out that processing the class names in the autoloader took more than 40% of the overall script execution time. APC did not help here, because despite the opcode caching, the autoloading function still must be called in order to see, what opcode should be actually loaded. This is why choosing a proper autoloader for our project is so important.
This text is licensed under Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States license.