I want to install a third-party PHP class for my application. How should I do that in Yii2? I could not find anything in the documentation.
4 Answers
Like FIMAk said it is well documented in docs but still it wasn't very clear how to me how to use downloaded library with autoloader class. So here is what I done:
1) create new folder in vendor directory and put library there
2) require autoloader in entry script before Yii is included, in case of basic application template it is path_to_yii_installation/web/index.php
For example, in one of the projects on which I worked before I had requirement to generate Excel sheets, I found that PHPExcel is best library to do this. So I included PHPExcel autoloader like this:
require(__DIR__ . '/../vendor/excel/PHPExcel.php');
My complete index.php file looks like this:
<?php
// comment out the following two lines when deployed to production
// defined('YII_DEBUG') or define('YII_DEBUG', true);
// defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../vendor/excel/PHPExcel.php');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();
3) at the top of your controller, model, or wherever you want to use library add use LibraryClassName and that is it.
2 Comments
Actually it is good described in the documentation.
You can find out how to install:
- using composer;
- using Downloaded Libraries;
- If a library carries its own class autoloader;
- If a library does not provide a class autoloader, but its class naming follows PSR-4;
- And if neither of the above is the case;