I want to configure Global Params
in Yii2.
For example this:
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/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.
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',
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With