Cache a Class Loader

Version: 2.2
Edit this page

Warning: You are browsing the documentation for Symfony 2.2, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

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 ApcClassLoader and the 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 added in Symfony 2.1.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
require_once '/path/to/src/Symfony/Component/ClassLoader/ApcClassLoader.php';

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

// my_prefix is the APC namespace prefix to use
$cachedLoader = new ApcClassLoader('my_prefix', $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 added in Symfony 2.1.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
require_once '/path/to/src/Symfony/Component/ClassLoader/XcacheClassLoader.php';

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

// my_prefix is the XCache namespace
$cachedLoader = new XcacheClassLoader('my_prefix', $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.