Page 1 of 1

Open Power Autoloader

Posted: Wed Feb 02, 2011 6:45 am
by Zyxist
Open Power Autoloader is my new project which aims to create a collection of very fast autoloaders compatible with PSR-0 class naming convention used by a number of PHP projects. It originated from my normal work, when I noticed that the autoloaders I was using put an extreme overhead over the web application and I started wondering, how to make them faster. Actually, I even showed one fast algorithm here a couple of months ago and it is implemented in Open Power Autoloader.

Structure

The library brings three autoloader classes designed for different purposes, together with some extra management tools. These are the autoloaders:

* Opl\Autoloader\GenericLoader - this is the standard autoloader that translates the class names to paths dynamically. It is intended to be used in the development environments and low-to-medium-volume websites.
* Opl\Autoloader\ClassMapLoader - this autoloader uses a precomputed class map loaded into the memory at the startup. It is designed for the most demanding services, where every fraction of second is important.
* Opl\Autoloader\PHARLoader - the autoloader for self-contained PHAR archives with web or console applications (but not libraries and frameworks). It is a simplified version of ClassMapLoader based on the assumption that the contents of the generated archive do not change, and the paths within the archive are constant.

In addition, there is a class for building the class maps and Symfony 2 Console command that does the same.

Sample usage

Example usage:

Code: Select all

<?php
require('../src/Opl/Autoloader/GenericLoader.php');
$loader = new Opl\Autoloader\GenericLoader('../src/');
$loader->addNamespace('Opl');
$loader->addNamespace('Symfony');
$loader->addNamespace('Doctrine');
$loader->addNamespace('Application', '../app/');
$loader->register();
Benchmark

I made a benchmark, where the autoloaders had to load and initialize 200 classes grouped in 10 libraries. Each test was repeated 20 times, the worst time was truncated and then I calculated the average time:

* Manual class loading: 0.0907 s
* OPL Class map loader: 0.1005 s
* OPL Generic Loader: 0.1218 s
* Doctrine 2 Class Loader: 0.1450 s (not fully compatible with PSR-0)
* SPL Class Loader (PHP impl.): 0.1649 s
* Symfony 2 Universal Class Loader: 0.1826 s
* Zend Framework 1.11 Loader: 0.2092 s

Issues

* The autoloader can be also used for the legacy code written in PHP 5.2.
* Contrary to some other universal autoloaders, we can register only the top-level namespaces. $loader->addNamespace('Foo\\Bar', '../src/'); will not work here, but this is an intended effect, becuase it is responsible for the much greater performance.

Resources

* GitHub hosting
* Download
* Documentation

Any feedback is much appreciated.