Yii2 third-party PHP class

I want to install a third-party PHP class for my application. How do I do this in Yii2? I could not find anything in the documentation.

+6
source share
4 answers

An easy way to do this is to simply register your class in any namespaces defined by Yii2 and use it in the file as use app\namespace\classname;

+6
source

This is actually well described in the documentation .

You can learn how to install:

  • using composer;
  • using downloaded libraries;
    • If the library carries its own class autoloader,
    • If the library does not provide a class autoloader, but its class name follows PSR-4;
    • And if it’s not,
+3
source

Like FIMAk, it is well documented in documents, but still it was not entirely clear how to use the loaded library with the autoloader class. So here is what I did:

1) create a new folder in the vendor directory and place the library there

2) an autoloader is required in the script input before Yii is enabled, in the case of the basic application template, this is path_to_yii_installation/web/index.php

For example, in one of the projects that I worked on before I had a requirement to generate Excel worksheets, I found that PHPExcel is the best library for this. Therefore, I enabled the PHPExcel autoloader as follows:

require(__DIR__ . '/../vendor/excel/PHPExcel.php');

My full index.php file is as follows:

 <?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 the library, add use LibraryClassName , and that’s all.

+3
source

add third-party lib to composer.json and click one command

  composer update 

always go for composer-based libs.

+2
source

Source: https://habr.com/ru/post/959405/


All Articles