Autoloading: Symfony vs Yii

PHP Autoloading consists about including files in an automated manner, using the __autoload magic function which is automatically called if there is a class or a interface that hasn’t been defined yet. This is the recommended aproach instead of using a long list of includes at the beginning of each file.

Both symfony 1 and Yii implement autoloading to avoid you the annoyances of requiring files by hand. Let’s see how each one implements it for you:

Yii way

In Yii, you have to indicate the autoloading paths for the framework to autoload the classes. Let’ see a Yii project structure to explain this better:

Yii project structure

Here you can see a common folder structure within a Yii project. Notice the protected folder is the one where you should put private files.

The file where you indicate the autoloading paths is project/protected/config/main.php, let’s see it:

  return array(
    'name'=>'My Project',
    // preloading 'log' component
    'preload'=>array('log', 'doctrine'),
    // autoloading model and component classes

As you can see, the import array has the information about what to autoload in the current project. For example the models folder has two subfolders, form and generated. I added form to put there my custom forms and generated was need to hold the base classes of the model with the Doctrine Framework. Each folder and subfolder has to be indicated in the import array to have the autoloading feature.

Symfony way

This is my favorite, because you don’t have to indicate with each new folder its location to autoload it. Let´s see a symfony 1 project structure to explain this:

Yii project structure

In symfony 1 there is a set of folders where you can put any subfolder or class, and everything will be autoload. This set of folder is the one with the lib name. There is a project lib folder, in this case project/lib. As you can see I like to recreate the symfony framework structure here with actions, controller, doctrine, filter, util folders. The filter, form and model folders are created by default.

If there is some class that belongs to an application instead of the whole project, symfony provides a lib folder per application following the same principle. For example: project/apps/backend/lib.

Finally you can provide a lib folder on a module basis. This folder will autoload the files the same way. For example: project/apps/backend/modules/article/lib.

Beware when using the app and module lib autoloading because if you need to instantiate a class in the frontend app, but you put it in the backend app, then this will be impossible unless you move this class to the project lib folder.

In this post was explained how both frameworks, symfony 1 and Yii, implement autoloading, each one in its own way. Each implementation having its pros and cons.

Leave a Reply

Your email address will not be published. Required fields are marked *