yii入门

jianfly.com 2019-01-31 1304次浏览

<?php
//新建控制器
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller {
	public function actionIndex() {  }
}
//yii获取请求参数
$request = \YII::$app->request;
$id = $request->get('id');
$id = $request->get('id', 20);//默认20
$id = $request->post('name');
$id = $request->post('name', 1111);
if($request->isGet) { //判断请求类型
	echo "this is get method!";
}
if($request->isPost) { //判断请求类型
	echo "this is post method!";
}
echo $request->userIp;//获取用户ip

//响应处理
$res = \YII::$app->response;
$res->statusCode = '404';//返回404状态码,默认返回200
$res->headers->add('pragma', 'no-cache');//不缓存消息
$res->headers->set('pragma', 'max-age=5');//缓存5s
$res->headers->remove('pragma');//删除
$res->headers->add('location', 'http://www.baidu.com');//跳转百度
$this->redirect('http://www.baidu.com', 302);//跳转百度,302为状态码
$res->headers->add('content-disposition', 'attachment; filename="a.jpg"');//文件下载
$res->sendFile('./b.jpg');//文件下载

//session处理
$session = \YII::$app->session;
$session->open();//开启session
if( $session->isActive ) { echo 'session is start'; } //判断session开启状态
$session->set('user', '张三');//存session
echo $session->get('user');//取出数据
$session->remove('user');//删除
$session['user'] = '张三';//存的另一种方法
echo $session['user'];//取
unset($session['user']);//删除

//cookie
use yii\web\Cookie;
$cookies = \YII::$app->response->cookies;
$cookie_data = array('name'=>'user', 'value'=>'zhangsan');
$cookies->add(new Cookie($cookie_data));//写,也能修改
$cookies->remove('user');//删除
$cookies2 = \YII::$app->request->cookies;
echo $cookies2->getValue('user');//取数据
echo $cookies2->getValue('users',20);//默认值

//视图
return $this->renderPartial('index');//显示index.php
$hello_str = 'Hello God';
$data = array();
$data['view_hello_str'] = $hello_str;
return $this->renderPartial('index', $data);//传递数据
/*<?= $view_hello_str; ?> //视图中使用数据*/
$test_arr = array(1, 2);//传递数组
$data['view_test_arr'] = $test_arr;
/* <?= $view_test_arr[0]; ?> */

//转义
/*
<?php use yii\helpers\Html; ?>
<?= Html::encode($view_hello_str); ?>
转义标签
*/  
/*
<?php use yii\helpers\HtmlPurifier; ?>
<?= HtmlPurifier::process($view_hello_str); ?>
去除标签及其内部元素
*/ 

public $payout = 'common';
return $this->render('index');//将index.php放入$content中  common中输出content

echo $this->render('about'); //在index.php中输出about.php的内容
echo $this->render('about', array('v_hello_str'=>'hello world')); //传递数据

//数据块
$this->beginBlock('block1');
	//内容。。。
$this->endBlock();
$this->bocks['block1'];//输出数据块
if(isset($this->bocks['block1'])) {} //判断