要改變應用程式的默認路由,應該配置 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,會看到下麵結果。

