Yii - 建立頁面



現在我們將建立一個“Hello world”頁面到您的應用程式中。要建立頁面,我們必須建立一個操作和一個檢視。

操作在控制器中宣告。終端使用者將收到操作的執行結果。

步驟 1 − 在現有的SiteController中宣告speak操作,它在類檔案controllers/SiteController.php中定義。

<?php 
   namespace app\controllers; 
   use Yii; 
   use yii\filters\AccessControl; 
   use yii\web\Controller; 
   use yii\filters\VerbFilter; 
   use app\models\LoginForm; 
   use app\models\ContactForm; 
   class SiteController extends Controller { 
      /* other code */ 
      public function actionSpeak($message = "default message") { 
         return $this->render("speak",['message' => $message]); 
      } 
   } 
?>

我們將speak操作定義為一個名為actionSpeak的方法。在Yii中,所有操作方法都以action開頭。這就是框架區分操作方法和非操作方法的方式。如果操作ID需要多個單詞,則它們將用短劃線連線。因此,操作ID add-post對應於操作方法actionAddPost

在上面給出的程式碼中,‘out’函式獲取一個GET引數$message。我們還呼叫一個名為‘render’的方法來渲染名為speak的檢視檔案。我們將message引數傳遞給檢視。渲染結果是一個完整的HTML頁面。

檢視是一個生成響應內容的指令碼。對於speak操作,我們建立一個列印我們訊息的speak檢視。當呼叫render方法時,它會查詢名為view/controllerID/vewName.php的PHP檔案。

步驟 2 − 因此,在views/site資料夾內建立一個名為speak.php的檔案,內容如下。

<?php 
   use yii\helpers\Html; 
?> 
<?php echo Html::encode($message); ?> 

請注意,我們在列印之前對message引數進行了HTML編碼,以避免XSS攻擊。

步驟 3 − 在您的Web瀏覽器中輸入https://:8080/index.php?r=site/speak&message=hello%20world

您將看到以下視窗:

Speak PHP File

URL中的‘r’引數代表路由。路由的預設格式是controllerID/actionID。在我們的例子中,路由site/speak將由SiteController類和speak操作解析。

廣告