Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure global uploadPath and uploadUrl in Yii2?

I want to configure Global Params in Yii2.

For example this:

  1. This will store the server path for all your file uploads.

Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/';

  1. This will store the Url pointing to server location for your file uploads.

Yii::$app->params['uploadUrl'] = Yii::$app->urlManager->baseUrl . '/uploads/';

When I set params like this:

'uploadPath' => Yii::$app->basePath . '/uploads/',
'uploadUrl' => Yii::$app->urlManager->baseUrl . '/uploads/',

I am getting this error:

Notice: Trying to get property of non-object

I did this for uploadPath and its working:

'uploadPath' => Yii::getAlias('@common') . '/uploads/',

But I can't get the uploadUrl and print the image. Please help, how will I set global uploadUrl in params.

like image 808
Mohit Bhansali Avatar asked Mar 30 '15 11:03

Mohit Bhansali


1 Answers

Actually Application object Yii::$app does not exist at the moment of applying configuration. To be exact, it's created from that config and then will run.

So you can not set these params through config and should do this in other place, for example during application bootstrap.

To implement this with application boostrap:

1) Create custom class let's say called app\components\Bootstrap:

namespace app\components;

use yii\base\BootstrapInterface;

class Bootstrap implements BootstrapInterface
{
    public function bootstrap($app)
    {
        // Here you can refer to Application object through $app variable
        $app->params['uploadPath'] = $app->basePath . '/uploads/';
        $app->params['uploadUrl'] => $app->urlManager->baseUrl . '/uploads/';
    }     
}

2) Include it in boostrap section in application config:

'bootstrap' => [
    ...
    'app\components\Bootstrap',
];
like image 92
arogachev Avatar answered Sep 19 '22 12:09

arogachev