YII框架學習筆記之命名空間、操作響應與視圖操作示例
本文實例講述了YII框架命名空間、操作響應與視圖操作。分享給大家供大家參考,具體如下:
YII基礎準備
1.命名空間
<?php /****假設有三個同名的類,輸出的值為A,B,C****/ use a\b\c\apple; use d\e\f\apple as bApple; use g\h\i\apple; $app = new apple();//A $app = new bApple();//B $app = new \Apple();//C 調用的是全局的
2.操作響應
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
{
public function actionIndex()//不叫方法叫操作
{
$request = \YII::$app->request;//能夠獲取到url值
echo $request->get('id',20);//如果沒有傳參可以設置默認值
if($request->isGet) //isPut
{
echo "this is get method";
}
echo $request->userIP;//獲取用戶IP
$res = \YII::$app->response;//獲取響應狀態(tài)
$res->statusCode = 404;//人為設置響應狀態(tài)碼
//$res->headers->add('pragma','no-cache');//設置head不設置緩存
$res->headers->set('pragma','max-age=5');//設置head緩存5分?秒鐘
$res->headers->remove('pragma');
//跳轉
$res->headers->add("location","http://www.baidu.com");
$this->redirect("http://www.baidu.com",302);
//文件下載
$res->headers->add('content-disposition','attachment;filename="a.jpg"');
$res->sendFile("robots.txt");
}
}
3. Yii視圖操作
<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller
{
public function actionIndex()
{
$hellp_str = "hello God!";
$data = array();
$data["view_hello_str"] = $hello_str;
return $this->renderPartial("index",$data);
}
}
?>
views\hello\index.php
$helper_str = "hello world!<script>console.log(111);</script>"
<?php
use yii\helpers\Html;//轉義
use yii\helpers\HtmlPurifier;//過濾html
<h1><?= Html::encode($view_hello_str);?></h1> <!--Html::encode() 能防止跨站腳本攻擊,轉義html標簽-->
<h1><?= HtmlPurifier::process($view_hello_str);?></h1>
<?= $this->render('_overview') ?><!--在一個視圖中調用另一個視圖-->
禁用布局
控制器內控制:
public $layout=false/'layout'
控制器成員方法內控制:
$this->layout=false/'layout'
視圖中選擇布局:
$this->context->layout=false/'layout'
更多關于Yii相關內容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結》、《php優(yōu)秀開發(fā)框架總結》、《smarty模板入門基礎教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
相關文章
Laravel框架實現(xiàn)利用監(jiān)聽器進行sql語句記錄功能
這篇文章主要介紹了Laravel框架實現(xiàn)利用監(jiān)聽器進行sql語句記錄功能,結合實例形式分析了Laravel框架監(jiān)聽器的創(chuàng)建、引入以及使用監(jiān)聽器記錄sql語句的相關操作技巧,需要的朋友可以參考下2018-06-06
PHP下用Swoole實現(xiàn)Actor并發(fā)模型的方法
這篇文章主要介紹了PHP下用Swoole實現(xiàn)Actor并發(fā)模型的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06
php+mysql+ajax 局部刷新點贊/取消點贊功能(每個賬號只點贊一次)
這篇文章主要介紹了php+mysql+ajax 局部刷新點贊/取消點贊功能(每個賬號只點贊一次),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
使用Yii2實現(xiàn)主從數(shù)據(jù)庫設置
大家應該都知道,當項目做大了,數(shù)據(jù)庫主從還是不可少的。使用Yii框架開發(fā),如何設置數(shù)據(jù)庫的主從呢?其實很簡單。下面這篇文章就給大家詳細介紹了使用Yii2實現(xiàn)主從數(shù)據(jù)庫設置的方法,文中介紹的很詳細,相信對大家的理解和學習很有幫助,下面來一起學習學習吧。2016-11-11

