Fork me on GitHub

Kris Wallsmith

Symfony Guru at opensky.com.
Discussing web development, Symfony and fatherhood.

Oct 24

Keep a trim autoloader

The symfony 1.4 autoloader works by scanning your PHP class files and remembering where each class and interface is defined, so it can magically load it when needed. This class-to-filename mapping is stored as an array in your application’s cache directory.

You can (and should) look at this array by opening this cache file in your text editor from time to time: cache/%SF_APP%/%SF_ENVIRONMENT%/config/config_autoload.yml.php. Inside you’ll see a big array with // comment headers.

<?php
// auto-generated by sfAutoloadConfigHandler
// date: 2010/10/24 05:29:41
return array(

  // sfDoctrineGuardPlugin_lib
  'pluginsfguardgroupformfilter' => '/path/to/plugins/sfDoctrineGuardPlugin/lib/filter/doctrine/PluginsfGuardGroupFormFilter.class.php',
  'pluginsfguardpermissionformfilter' => '/path/to/plugins/sfDoctrineGuardPlugin/lib/filter/doctrine/PluginsfGuardPermissionFormFilter.class.php',
  'pluginsfguarduserformfilter' => '/path/to/plugins/sfDoctrineGuardPlugin/lib/filter/doctrine/PluginsfGuardUserFormFilter.class.php',

  // ...

A few things to look for in this file:

  1. You should not see any reference to libraries that have their own autoloader. This includes the symfony core classes, Swiftmailer, Zend Framework, etc. If you see references to classes from one of these libraries, your autoloader is not configured correctly.
  2. You should not see any non-runtime classes.

You’ll probably need to add some configuration to accomplish that second point. For example, your tasks and Doctrine migration classes will never be involved in a runtime request, so they should not be included in the autoloader’s cache.

Configure the autoloader

Fortunately, excluding these files is easy enough using autoload.yml.

Add this file to your project…

# config/autoload.yml
autoload:
  # extend the "project" configuration block defined in the symfony core
  project:
    exclude: [vendor, symfony, model, migration, task]

Clear your cache…

$ php symfony cache:clear

Visit your site in the browser to prime the cache, and re-inspect the cached config_autoload.yml.php file. Your task and Doctrine migration classes should no longer be represented there.

Add this to your installer

The new installer mechanism in symfony 1.4 is the perfect place to add this sort of thing since you’re going to want to do it on every project. For an example of how this is done, check out commit dede92e on my GitHub symfony-installer project.

Read more

If you want to learn more about configuring the symfony 1.4 autoloader, please read through The symfony Reference Guide, specifically the section on autoload.yml.


  1. kriswallsmith posted this