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 showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

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

The PSR-0 Class Loader

2.8 version
Maintained Unmaintained

The PSR-0 Class Loader

If your classes and third-party libraries follow the PSR-0 standard, you can use the Symfony\Component\ClassLoader\ClassLoader class to load all of your project’s classes.


You can use both the ApcClassLoader and the XcacheClassLoader to cache a ClassLoader instance.


Registering the Symfony\Component\ClassLoader\ClassLoader autoloader is straightforward:

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

use Symfony\Component\ClassLoader\ClassLoader;

$loader = new ClassLoader();

// to enable searching the include path (eg. for PEAR packages)

// ... register namespaces and prefixes here - see below


Use addPrefix() or addPrefixes() to register your classes:

// register a single namespaces
$loader->addPrefix('Symfony', __DIR__.'/vendor/symfony/symfony/src');

// registers several namespaces at once
    'Symfony' => __DIR__.'/../vendor/symfony/symfony/src',
    'Monolog' => __DIR__.'/../vendor/monolog/monolog/src',

// registers a prefix for a class following the PEAR naming conventions
$loader->addPrefix('Twig_', __DIR__.'/vendor/twig/twig/lib');

    'Swift_' => __DIR__.'/vendor/swiftmailer/swiftmailer/lib/classes',
    'Twig_'  => __DIR__.'/vendor/twig/twig/lib',

Classes from a sub-namespace or a sub-hierarchy of PEAR classes can be looked for in a location list to ease the vendoring of a sub-set of classes for large projects:

    'Doctrine\Common'          => __DIR__.'/vendor/doctrine/common/lib',
    'Doctrine\DBAL\Migrations' => __DIR__.'/vendor/doctrine/migrations/lib',
    'Doctrine\DBAL'            => __DIR__.'/vendor/doctrine/dbal/lib',
    'Doctrine'                 => __DIR__.'/vendor/doctrine/orm/lib',

In this example, if you try to use a class in the Doctrine\Common namespace or one of its children, the autoloader will first look for the class under the doctrine-common directory. If not found, it will then fallback to the default Doctrine directory (the last one configured) before giving up. The order of the prefix registrations is significant in this case.

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