Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 2.3 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

Cache a Class Loader

2.3 version
Maintained Unmaintained

Cache a Class Loader

Introduction

Finding the file for a particular class can be an expensive task. Luckily, the ClassLoader component comes with two classes to cache the mapping from a class to its containing file. Both the Symfony\Component\ClassLoader\ApcClassLoader and the Symfony\Component\ClassLoader\XcacheClassLoader wrap around an object which implements a findFile() method to find the file for a class.

Note

Both the ApcClassLoader and the XcacheClassLoader can be used to cache Composer’s autoloader.

ApcClassLoader

New in version 2.1: The ApcClassLoader class was introduced in Symfony 2.1.

ApcClassLoader wraps an existing class loader and caches calls to its findFile() method using APC:

require_once '/path/to/src/Symfony/Component/ClassLoader/ApcClassLoader.php';

// instance of a class that implements a findFile() method, like the ClassLoader
$loader = ...;

// sha1(__FILE__) generates an APC namespace prefix
$cachedLoader = new ApcClassLoader(sha1(__FILE__), $loader);

// register the cached class loader
$cachedLoader->register();

// deactivate the original, non-cached loader if it was registered previously
$loader->unregister();

XcacheClassLoader

New in version 2.1: The XcacheClassLoader class was introduced in Symfony 2.1.

XcacheClassLoader uses XCache to cache a class loader. Registering it is straightforward:

require_once '/path/to/src/Symfony/Component/ClassLoader/XcacheClassLoader.php';

// instance of a class that implements a findFile() method, like the ClassLoader
$loader = ...;

// sha1(__FILE__) generates an XCache namespace prefix
$cachedLoader = new XcacheClassLoader(sha1(__FILE__), $loader);

// register the cached class loader
$cachedLoader->register();

// deactivate the original, non-cached loader if it was registered previously
$loader->unregister();

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.