溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Yii 框架怎么創(chuàng)建一個控制器

發(fā)布時間:2021-03-23 16:20:36 來源:億速云 閱讀:169 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)使用Yii 框架怎么創(chuàng)建一個控制器,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

Yii 框架控制器創(chuàng)建使用

在根目錄下的controllers目錄下創(chuàng)建控制器HelloController.php:

<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller{
  //方法必須以action開頭
  public function actionIndex(){
    echo 'hello';
  }
}

訪問地址:basic/web/index.php?r=hello/index

參數(shù)r后邊跟控制器名字/方法名字。

如果需要傳遞參數(shù):

<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller{
  //方法必須以action開頭
  public function actionIndex(){
    $request = \YII::$app->request;
    $id = $request->get('id','');//第二個參數(shù)是如果沒有傳遞怎么處理
    echo 'hello,id=' . $id;
    //判斷是否是get或post請求
    if($request->isGet){
      echo 'get';
    }
    if($request->isPost){
      echo 'post';
    }
    //獲取用戶地址
    echo $request->userIP;
  }
}

Yii 框架控制器響應(yīng)

  public function actionIndex(){
    //控制器響應(yīng)處理
    $res = \Yii::$app->response;
    //設(shè)置狀態(tài)碼
//    $res->statusCode = '404';
    //設(shè)置header頭
//    $res->headers->add('pragma','no-cache');//增加
//    $res->headers->set('pragma','max-age=5');//修改
//    $res->headers->remove('pragma');//刪除
    //跳轉(zhuǎn)
    //方法一
//    $res->headers->add('location','http://www.baidu.com');
    //方法二
//    $this->redirect('http://www.baidu.com');
    //文件下載
    //方法一
//    $res->headers->add('content-disposition','attachment;filename=a.jpg');
     //方法二
//    $res->sendFile('./robots.txt');
  }

關(guān)于使用Yii 框架怎么創(chuàng)建一個控制器就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

yii
AI