如何在Yii2中配置全局uploadPath和uploadUrl? [英] How to configure global uploadPath and uploadUrl in Yii2?

查看:371
本文介绍了如何在Yii2中配置全局uploadPath和uploadUrl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Yii2中配置Global Params.

I want to configure Global Params in Yii2.

例如:

  1. 这将存储所有文件上传的服务器路径.

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

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

  1. 这将存储指向服务器上载文件的网址.

Yii :: $ app-> params ['uploadUrl'] = Yii :: $ app-> urlManager-> baseUrl. '/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/',

我收到此错误:

注意:尝试获取非对象的属性

Notice: Trying to get property of non-object

我这样做是为了uploadPath及其工作:

I did this for uploadPath and its working:

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

但是我无法获取uploadUrl并打印图像.请帮忙,我将如何在参数中设置全局uploadUrl.

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

推荐答案

实际上,在应用配置时,应用程序对象Yii::$app不存在.确切地说,它是从该配置创建的,然后将运行.

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.

因此,您不能通过config设置这些参数,而应在其他地方执行此操作,例如在应用程序引导期间.

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

要使用应用程序boostrap来实现此目的:

To implement this with application boostrap:

1)创建自定义类,我们称其为app\components\Bootstrap:

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)将其包括在应用程序配置的boostrap部分中:

2) Include it in boostrap section in application config:

'bootstrap' => [
    ...
    'app\components\Bootstrap',
];

这篇关于如何在Yii2中配置全局uploadPath和uploadUrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆