在Web應用程式中控制器應該從 yii\web\Controller 或其子類擴展。在控制臺應用程式,它們應該從 yii\console\Controller 或其子類擴展。
讓我們在 Controllers 檔夾創建一個控制器實例。
第1步 - 在 Controllers 檔夾中,創建一個名為 ExampleController.php,使用下麵的代碼。
<?php namespace app\controllers; use yii\web\Controller; class ExampleController extends Controller { public function actionIndex() { $message = "index action of the ExampleController"; return $this->render("example",[ 'message' => $message ]); } } ?>
第2步 - 在 views/example 檔夾中創建一個 example 視圖。在該檔夾內,創建一個名為 example.php 視圖檔,使用下麵的代碼檔。
<?php echo $message; ?>
每個應用程式都有一個默認的控制器。對於Web應用程式,site是默認的控制器,而控制臺應用程式則是help。因此,當URL=>http://localhost:8080/index.php 被打開時,site 控制器將處理請求。當然你也可以更改應用程式配置默認的控制器。
考慮給定的代碼 -
'defaultRoute' => 'main'
步驟3 - 將上述的代碼添加到下麵檔 : config/web.php.
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is //required by cookie validation 'cookieValidationKey' => 'xuhuhu.com', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'db' => require(__DIR__ . '/db.php'), ], //changing the default controller 'defaultRoute' => 'example', 'params' => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', ]; } return $config; ?>
注 - 控制器ID應包含小寫字母,數字,斜線,連字元英文字母和下劃線。
要將控制器ID轉換控制器類的名字,應該做到以下幾點 -
- 以連字元分隔所有單詞的第一個字母,把它變成大寫
- 刪除連字元
- 替換反向斜線
- 添加Controller尾碼
- 前面加上控制器命名空間
示例
-
page 變成 app\controllers\PageController.
-
post-article 變成 app\controllers\PostArticleController.
-
user/post-article 變成 app\controllers\user\PostArticleController.
-
userBlogs/post-article 變成 app\controllers\userBlogs\PostArticleController.