Yii - how to access the base URL in main config

11,385

You're right, you can't use the Yii::app() methods inside the config's return array, but you can use Yii::getPathOfAlias() outside. Something like this might work:

$webroot = Yii::getPathOfAlias('webroot');
return array(
    ...
    'params'=>array(
        'paths' => array(
            'imageTemp'=> $webroot.'/files/temp-',
            'image'=> $webroot.'/files/',
            ...
        ),
    ),
);

Assuming webroot is defined beforehand.

As for baseUrl... I'll come back to you on that one!

[Back...]

If you need a url, it all depends where your images files are being kept, relative to the yii path, or relative to the base of the web root?

If the base of the web root, you could just use:

return array(
    ...
    'urls'=>array(
        'paths' => array(
            'imageTemp'=> '/files/temp-',
            'image'=> '/files/',
            ...
        ),
    ),
);
Share:
11,385
mahsa.teimourikia
Author by

mahsa.teimourikia

PhD in Computer Science, passionate about data science and machine learning.

Updated on July 26, 2022

Comments

  • mahsa.teimourikia
    mahsa.teimourikia over 1 year

    I am working on a Yii application. I am trying to set some paths in my main config params like this:

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
           'paths' => array(
                'imageTemp'=> Yii::getPathOfAlias('webroot').'/files/temp-',
                'image'=> Yii::getPathOfAlias('webroot').'/files/',
                ...
            ),
    
            'urls' => array(
                'imageTemp'=> Yii::app()->getBaseUrl().'/files/temp-',
                'image'=> Yii::app()->getBaseUrl().'/files/',
                ...
            ),
    

    But I am getting this error:

    Fatal error: Call to a member function getBaseUrl() on a non-object in ..blahblah../base/CApplication.php on line 553
    

    I think I cannot use Yii::app() in config file since the app is not initialized yet here, or something like this. So, how can I replace Yii::app()->getBaseUrl() in the config file and get the same results?