在 Yii 2 中获取基本 URL [英] Getting base URL in Yii 2

查看:24
本文介绍了在 Yii 2 中获取基本 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Yii 2 中获取项目的基本 URL,但它似乎不起作用.根据 这个页面 你曾经能够做到:

I am trying to get the base URL for the project in Yii 2 but it doesn't seem to work. According to this page you used to be able to do:

Yii::app()->getBaseUrl(true);

在 Yii 1 中,但似乎 Yii 2 中的那个方法不再接受参数?

In Yii 1, but it seems that that method in Yii 2 no longer accepts a parameter?

我试过在没有 true 的情况下这样做,例如:

I've tried doing it without true, such as:

Yii::$app->getBaseUrl();

但它只是返回空.

你怎么能在 Yii 2 中做到这一点?

How can you do this in Yii 2?

推荐答案

要获取应用程序的基本 URL,您应该使用 yii\helpers\Url::base() 方法:

To get base URL of application you should use yii\helpers\Url::base() method:

use yii\helpers\Url;

Url::base();         // /myapp
Url::base(true);     // http(s)://example.com/myapp - depending on current schema
Url::base('https');  // https://example.com/myapp
Url::base('http');   // http://example.com/myapp
Url::base('');       // //example.com/myapp

Url::home() 在这种情况下不应该使用.Application::$homeUrl 默认使用基本 URL,但可以轻松更改(例如更改为 https://example.com/myapp/home),因此您不应该依赖于它总是会的假设返回基本 URL.如果有特殊的 Url::base() 方法来获取基本 URL,则使用它.

Url::home() should NOT be used in this case. Application::$homeUrl uses base URL by default, but it could be easily changed (for example to https://example.com/myapp/home) so you should not rely on assumption that it will always return base URL. If there is a special Url::base() method to get base URL, then use it.

这篇关于在 Yii 2 中获取基本 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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