要改变应用程序的默认路由,应该配置 defaultRoute 属性。
步骤1- 以下列方式修改 config/web.php 文件。
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'defaultRoute' => 'site/contact', 'components' => [ //other code ?>
如要把应用程序暂时开启维护模式,应该配置 yii\web\Application::$catchAll 这个属性。
第3步 - 添加以下 actionMaintenance() 函数到 SiteController
public function actionMaintenance() { echo "<h1>系统正在维护中...</h1>"; }
步骤4 - 然后,以下面的方式修改config/web.php 文件 。
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'catchAll' => ['site/maintenance'], 'components' => [ //OTHER CODE
第5步 - 进入应用程序中的任何URL,会看到以下内容。


创建URL
要创建各种URL,可以使用 yii\helpers\Url::to() 辅助方法。下面的例子假定使用的是默认的URL格式。
第1步- 在 SiteController 添加一个 actionRoutes() 方法。
public function actionRoutes() { return $this->render('routes'); }
这个方法只是简单地呈现的路由视图。
第2步 - 在 views/site 目录下,创建一个名为 routes.php文件,并使用下面的代码。
<?php use yii\helpers\Url; ?> <h4> <b>Url::to(['post/index']):</b> <?php // creates a URL to a route: /index.php?r = post/index echo Url::to(['post/index']); ?> </h4> <h4> <b>Url::to(['post/view', 'id' => 100]):</b> <?php // creates a URL to a route with parameters: /index.php?r = post/view&id=100 echo Url::to(['post/view', 'id' => 100]); ?> </h4> <h4> <b>Url::to(['post/view', 'id' => 100, '#' => 'content']):</b> <?php // creates an anchored URL: /index.php?r = post/view&id=100#content echo Url::to(['post/view', 'id' => 100, '#' => 'content']); ?> </h4> <h4> <b>Url::to(['post/index'], true):</b> <?php // creates an absolute URL: http://www.example.com/index.php?r=post/index echo Url::to(['post/index'], true); ?> </h4> <h4> <b>Url::to(['post/index'], 'https'):</b> <?php // creates an absolute URL using the https scheme: https://www.example.com/index.php?r=post/index echo Url::to(['post/index'], 'https'); ?> </h4>
第3步 - 打开浏览器URL访问:http://localhost:8080/index.php?r=site/routes,会看到 to()函数的一些用法

传递到 yii\helpers\Url::to()方法的路由可以是根据下面的规则使用相对或绝对路径 -
-
如果路由是空的,则使用当前所请求的路径
-
如果路由没有前导斜线,使用相对于当前模块的路由
-
如果根不包含斜线,使用当前控制器的动作ID。
yii\helpers\Url 助手类还提供了一些有用的方法。
第4步 - 修改路由视图 - views/site/routes.php 文件。按如下面给出的代码。
<?php use yii\helpers\Url; ?> <h4> <b>Url::home():</b> <?php // home page URL: /index.php?r=site/index echo Url::home(); ?> </h4> <h4> <b>Url::base():</b> <?php // the base URL, useful if the application is deployed in a sub-folder of the Web root echo Url::base(); ?> </h4> <h4> <b>Url::canonical():</b> <?php // the canonical URL of the currently requested URL // see https://en.wikipedia.org/wiki/Canonical_link_element echo Url::canonical(); ?> </h4> <h4> <b>Url::previous():</b> <?php // remember the currently requested URL and retrieve it back in later requests Url::remember(); echo Url::previous(); ?> </h4>
第5步 - 打开浏览器输入的地址:http://localhost:8080/index.php?r=site/routes,会看到下面结果。
