Quantcast
Channel: Richard Knop
Viewing all articles
Browse latest Browse all 20

Faster Autoloading With Zend Framework 2

$
0
0

Standard autoloader that comes with Zend Framework 2 is not and ideal one to use in production environment. I would suggest using a classmap autoloader which is faster. Here is how it works. When installing dependencies specified in composer.json, use -o option in order to generate classmap file:

php composer.phar install -o

It will create a PHP file at vendor/composer/autoload_classmap.php path which contains a static array of all knows classes from dependencies (Zend Framework 2, Doctrine 2 etc) with namespaces and paths to files.

You should also autoload all your modules in the same way. Either do it manually – cd into module folder and generate the classmap file:

cd module/Foo
../../vendor/bin/classmap_generator.php -w

Or use ANT:

<target name="classmapgenerator" description="">
		<exec executable="php">
			<arg value="${basedir}/vendor/zendframework/zendframework/bin/classmap_generator.php" />
			<arg value="-w" />
			<arg value="-l" />
			<arg value="module/Foo" />
		</exec>
		<exec executable="php">
			<arg value="${basedir}/vendor/zendframework/zendframework/bin/classmap_generator.php" />
			<arg value="-w" />
			<arg value="-l" />
			<arg value="module/Bar" />
		</exec>
	</target>

Inside your Module.php, change getAutoloaderConfig() method to look like this:

public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
        );
    }

Finally, change your init_autoloader.php file:

require_once __DIR__ . '/vendor/zendframework/zendframework/library/Zend/Loader/AutoloaderFactory.php';
require_once __DIR__ . '/vendor/zendframework/zendframework/library/Zend/Loader/ClassMapAutoloader.php';
Zend\Loader\AutoloaderFactory::factory(array(
    'Zend\Loader\ClassMapAutoloader' => array(
        'Composer' => __DIR__ . '/vendor/composer/autoload_classmap.php',
    )
));

Done! I don’t have any benchmarks at the moment. If I will have more free time, I will run some benchmarks to see how much faster it is actually.


Viewing all articles
Browse latest Browse all 20

Trending Articles