How to access namespace from Yii2 params.php

I need to set some configurations values into an XML file. The configuration key is set well in params.php as an array. I wrote a simple class to load the xml entities and turn them into array. I could not able to access this class from params.php in the config directory. It works fine from any controller like below:

use app\components\saidbakr\FoxXML;
...
public function actionIndex()
    {
        echo "<pre>";
        print_r(FoxXML::loadXMLFile(__DIR__.'/../config/values/readers.xml')['reader']);
die();
...

However, in params.php I tried:

<?php
use app\components\saidbakr\FoxXml;
$siteName = Yii::t('app','Site Name');
return [
    'closeSite...
...
'readers' => FoxXML::loadXMLFile(__DIR__.'/../config/values/readers.xml')['reader'],
...

I got class not found:

Fatal error: Uncaught Error: Class 'app\components\saidbakr\FoxXML' not found in /home/myuser/public/quran-yii2/config/params.php on line 62

Error: Class 'app\components\saidbakr\FoxXML' not found in /home/myuser/public/quran-yii2/config/params.php on line 62

I also tried to use the namespace in the entry script web/index.php use app\components\saidbakr\FoxXML; but I have the same issue.

How could I able to use a defined class methods in the configuration file? I'm using PHP 7.4.


By default the app namespace is resolved by Yii's autoloader and it uses @app alias to resolve it. But alias is not yet set when parsing your params.php config. That's causing the class not found error.

Easy solution is to add the app namespace as PSR-4 namespace into your composer.json config:

"autoload": {
    "psr-4": {
        "app\\": "."
    }
}

Then run composer dump-autoload. Thanks to that the loading of class in app namespace will be handled by composer autoloader which is already set up when config files are parsed.