Autoloading namespaced libraries in Yii Framework


To integrate libraries using namespaces into a Yii Framework project, you can simply use Yii::setPathOfAlias to have the classes autoloaded by Yii when needed. Just specify the root namespace as the alias and the physical location of that root alias as the path.

Using Predis as an example, if we put the code in:

/vendors/predis/lib/Predis

We’ll add it to Yii as an alias named Predis so classes under it can be autoloaded:

Yii::setPathOfAlias('Predis', '/vendors/predis/lib/Predis');

Now when we call new Predis\Client(), Yii will look for a file named Client.php in /vendors/predis/lib/Predis. The same holds true for other classes under subfolders (e.g. Predis\Commands\Append).