Using external PHP libraries with the Yii framework

Yii is an easy to use and flexible PHP5 framework. It comes with all essential functionality needed to quickly create any sort of web application. Because Yii is not intended to be an all-in-one solution, you can easily extend it to fit your needs. On the Yii web site there are several extensions available.

But you are not restricted to the use of Yii extensions. If there is an existing library out there you like, use it.

  1. Create a vendors folder in your application folder:
  2. Copy your libraries to the newly created vendors folder.
  3. Add the folder to your include path in your configuration file (protected/config/main.php):
  4. Yii uses the autoload functionality of PHP to automatically load scripts. For this to work in Yii, the file name must be equal to the class name. So for example, if you want to use Simplepie the script file must be named protected/vendors/Simplepie.php.

    You can then simply create an object in any controller with:

    $feed = new Simplepie;

    Simplepie uses the idna_convert class for international domain names. This class must also reside in the protected/vendors folder

But that is not all. You can also use library collections, like Zend Framework or eZ Components, that utilise PHP's autoload. And you can use them at the same time using spl_autoload_register().

The easiest place to register the libraries is in the entry script. This way they can be loaded from any controller.

  1. You first have to unregister Yii autoload, because Yii raises an error if a class isn't found.
  2. Next step is to include the autoload scripts and register the autoload functions of the libraries.
  3. The last step is to register Yii autoload again, so everything works as before.

The final entry script (index.php) will look like this:



// unregister Yii autoload

// register Zend Framework
spl_autoload_register(array('Zend_Loader_Autoloader', 'autoload'));

// register eZ Components
spl_autoload_register(array('ezcBase', 'autoload'));

// re-register Yii autoload
spl_autoload_register(array('YiiBase', 'autoload'));


Now you can create any object without worrying where the class scripts are located.