How to Use Third Party Autoloaders in Yii


Using third party libraries in Yii is super easy. Just put the library, e.g. Google, under vendors directory and add the following lines at the beginning in your controller where you wish to use it.

Alternatively, you can include the first line mentioned above in your Yii application’s main.php imports section as shown below (line 4).

And then include the desired file in your controller (2nd line) before using it. That’s all.

However, you might run into issues if you are integrating a third party library with it’s own autoloader. Yii’s guide has some documentation on how to tackle the situation but it doesn’t work out of the box for most of the people. The reason why integrating third party libraries with autoloaders in Yii isn’t as simple as integrating a non-autoloader library is that third party autoloaders conflict with Yii’s own autoloader.

In such a situation, you can use the code mentioned below and change the path/library as per your requirements in second line. You can use it anywhere in your code (most likely in controller) as needed.

Trick here is to temporarily unregister Yii’s autoload functionality before adding third party autoloader and then re-enabling Yii’s autoloader. You still need to include the vendors directory in your application’s main.php as shown in second code snippet above.

I am not sure if this works in Yii 2 as well, most likely it won’t since Yii 2 is a complete rewrite, but this certainly works in Yii 1.x releases.