Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - how to access the base URL in main config

Tags:

url

path

php

yii

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?

like image 692
mahsa.teimourikia Avatar asked Nov 07 '12 11:11

mahsa.teimourikia


People also ask

How to get URL in Yii2?

To get the base URL of the current request use the following: $relativeBaseUrl = Url::base(); $absoluteBaseUrl = Url::base(true); $httpsAbsoluteBaseUrl = Url::base('https'); The only parameter of the method works exactly the same as for Url::home() .

How to get value from URL in Yii2?

Yii::app()->request->getUrl(); Yii::app()->request->getParams('id'); $_GET['id'];

What is $App in Yii?

Applications are objects that govern the overall structure and lifecycle of Yii application systems. Each Yii application system contains a single application object which is created in the entry script and is globally accessible through the expression \Yii::$app .


1 Answers

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/',
            ...
        ),
    ),
);
like image 51
Stu Avatar answered Oct 02 '22 11:10

Stu