6

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.

1
  • This needs more information and context. Commented Dec 5, 2013 at 16:45

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Could you expand on step 2 by means of an example. My index.php has "require(DIR . '/../../vendor/autoload.php');" so does this mean that step is done?
@crafter better now?
3

Actually it is good described in the documentation.

You can find out how to install:

  1. using composer;
  2. 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;

Comments

2

add third party lib in composer.json and hit one command

 composer update

always go for composer based libs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.