How to check for existence of an extension?

Hello,

How do i know if an extension is loaded before I attempt to use it?

I have a case where in the production environment I do NOT have the contentCompactor extension installed but in the production I DO have it.

Trying to modify the Controller.php to , sometimes, use the compactor and other times do NOT use is confusing.

When I use:


$compactor = Yii::app()->contentCompactor;

it fails with:


CException


Property "CWebApplication.contentCompactor" is not defined.

Trying to see if it is defined with:


defined(Yii::app()->contentCompactor)

Still fails.

Is there another way to check if the contentCompactor extension is loaded before I use it?

Thanks

You can use:




Yii::app()->hasComponent('contentCompactor')



To see if the component is configured. However, it will also return true, if the component is configured but disabled.

Thanks,

That will do. In my case the component is either there or it’s not. I do not use the enabling or disabling functionality.

BTW, do you happen to know if we can also get access to the config array that we pass to the app during initialization? All the information of how the application is configured is also there.

From what I investigated, though it seems the config array is not kept as is but it is expanded with a foreach loop.

Maybe if there is another way?

Stratos

Reopening two years old topic…

If component being enabled or not is a matter, then instead of using hasComponent() it is better to check whether getComponent() returns NULL or not. According to documentation, it will return NULL, if the application component is disabled or does not exist. So, you can check this way, for any component that has to exists and has to be enabled in the same time.

Hello,

I was looking for some way to check if an extension is installed, so here is what I did:




    if (array_key_exists('kartik-v/yii2-grid', Yii::$app->extensions)){

        die('gridview found');

    } else {

        die('no gridview');

    }



I used Yii2 v2.0.12.

Regards.