<?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' => 'tw511.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; ?>
page 變成 app\controllers\PageController.
post-article 變成 app\controllers\PostArticleController.
user/post-article 變成 app\controllers\user\PostArticleController.
userBlogs/post-article 變成 app\controllers\userBlogs\PostArticleController.