目录 1.1 yii2目录结构 2 配置文件2.1 使用restful风格url #urlManager #重定向2.2 #catchAll 把所有请求都重定向到指定页面 #重定向 3
—#
1 安装yii2
composer create-project --prefer-dist yiisoft/yii2-app-basic yii
'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ ], ],
url
如果使用渲染函数转发到指定页面渲染,此时则无法在actionView()
方法内输出echo
,只能在指定页面进行输出
还可以使用render传递参数
输出包含html代码的变量,存在xss注入问题
注意:这里传参用
&id=2
而不是?id=2
读取cookie使用request,增删改cookie使用reponse
view
中的this
的字段context
,即$this->context
,指的是controller
中的$this
php var_dump($this->context->id); //输出Controller var_dump($this->context->action->id ); // 输出action var_dump($this->context->enc); // 输出Controller的成员变量
$this->reGISterjsFile('@WEB/js/test.js');?><button id="ajaxtest" onclick="submitAjax()">test</button>
public function actionAjax() { $id = $_GET['id']; $uid = $_POST['uid']; return JSON_encode(["id" => $id]); }
function submitAjax(){ $.post({ url:"Http://localhost/site/ajax?id=234324", data:{"uid":111111}, dataType: "json", success:function(data){ console.log(data); alert(data.id); } })}
使用ajax时,只需要加上
dataType: "json"
即可使用axios时,发送json数据,需要配置
web.php
,这样才能接受到json格式的数据
axios 发送的数据都是json格式的数据,而Yii2默认的配置是不能识别这种格式的,官方文档上已经做了说明,需要在web.php
下进行配置才能识别json数据。
为了使 api 接收 JSON 格式的输入数据,配置 request 应用程序组件的 parsers 属性使用 yii\web\JsonParser
用于JSON输入
'parsers' => [ 'application/json' => 'yii\web\JsonParser', 'text/json' => 'yii\web\JsonParser', ]
其他方式无法获取的参数,必须使用
request组价
接收参数,即\Yii::$app->request
axiostest() { axios.post("http://localhost/site/ajax",{ id:23432, uid:1111, } ) .then(res=>{ console.log(res.data.id); alert(res.data.id); })}
public function actionAjax() { $req = \Yii::$app->request; $id = $reqaxio定时器->post('id'); $uid = $req->post('uid'); return json_encode(["id" => $id,'uid'=>$uid]); }
$this->registerJsFile('@web/js/test.js');?><div id="app"> <button @click="axiostest()">test</button></div>
public function actionAjax() { $a = \Yii::$app->request; $id = $a->post('id'); $uid = $a->post('uid'); return json_encode(["id" => $id,'uid'=>$uid]); }
new Vue({ el:'#app', data: { param:{ 'id':23432, 'uid':1111, } }, methods: { axiostest() { axios.post("http://localhost/site/ajax",{ 'id':23432, 'uid':1111, } ) .then(res=>{ console.log(res.data.id); alert(res.data.id); }) } }})
Model对象放在models目录下
使用load()函数给model对象字段赋值,如果不符合字段值约束rules,也能赋值,但调用字段值校验函数validate()时会返回false
如果用表单控件
ActiveFORM
给model赋值,如果不符合字段值约束规则rules
,则无法提交表单,无法提交请求给后台处理
如果没有设置safe,则字段值必须要通过校验后,才能给字段赋值,否则无法给model赋值
trim不是校验规则
default不是校验规则
表单控件给model对象赋值,会自动触发字段校验validate()
表单如果没有写提交地址action,会默认提交给当前的action处理请求
ActiveForm提交默认使用post请求
model层
'tom',message=>'不为tom'], [['name','email'],required,message=>'必选字段'], [['email'],'email',message=>'不是邮箱'], ]; }}
controller层
load(Yii::$app->request->post()); // 获取post请求值 if ($model->validate()) { // 成功提交表单后 Yii::$app->session->setFlash("success", '提交表单成功'); // 提示框 } return $this->render(test2, ['model' => $model]); }}
视图层view:表单ActiveForm
= $form->field($model, 'name') ?> = $form->field($model, 'email') ?> = Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
namespace app\models;use yii\db\ActiveRecord;class Article extends ActiveRecord{ public static function tableName() // 设置要连接的表table { return 'test_my.rbid_change_info_test'; } public static function getDb() // 设置要连接的数据库 { return \Yii::$app->db01; }}
find()
返回的是对象ActiveQuery
,ActiveQuery
继承Query
,可以使用QueryBuilder继续查询操作
findAll()
、findOne
返回的是结果集数组
dml操作的函数都有返回值(影响的记录数)
save()可以用于插入/更新记录到数据库(推荐)
推荐使用save()实现插入、更新操作
save()会触发model对象的字段值验证rules,触发validate()
等价于:
createCommand()返回的是对象
test_my
下的表(dsn中指定了数据库)'dsn' => 'Mysql:host=localhost;dbname=test_my;port=2039'
return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=test_my;port=2039', // 可以指定要连接的数据库,可以不指定 'username' => 'apollo-rw', // 用户名 'passWord' => 'QBT094bt', // 密码 'charset' => 'utf8'];
test.tb1
'dsn' => 'mysql:host=localhost;port=2039'
return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;port=2039', // 可以指定要连接的数据库,可以不指定 'username' => 'apollo-rw', // 用户名 'password' => 'QBT094bt', // 密码 'charset' => 'utf8'];
return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;port=2039', 'username' => 'apollo-rw', 'password' => 'QBT094bt', 'charset' => 'utf8', 'tablePrefix' => 'tb_'];
// 返回多行. 每行都是列名和值的关联数组.// 如果该查询没有结果则返回空数组$posts = Yii::$app->db->createCommand('SELECT * FROM post') ->queryAll();// 返回一行 (第一行)// 如果该查询没有结果则返回 false$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=1') ->queryOne();// 返回一列 (第一列)// 如果该查询没有结果则返回空数组$titles = Yii::$app->db->createCommand('SELECT title FROM post') ->queryColumn();// 返回一个标量值,第一行第一列// 如果该查询没有结果则返回 false$count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM post') ->queryScalar();
写法一:
$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status') ->bindValue(':id', $_GET['id']) ->bindValue(':status', 1) ->queryOne();
写法二:
$params = [':id' => $_GET['id'], ':status' => 1];$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status') ->bindValues($params) ->queryOne();
写法三:推荐
$params = [':id' => $_GET['id'], ':status' => 1];$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status', $params) ->queryAll();// 等价于$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status', [':id' => $_GET['id'], ':status' => 1]) ->queryAll();
use Yii;public function actionTest(){$sql = "select * from rbid_change_info_test where from_rbid=:from_rbid";$res = Yii::$app->db01->createCommand($sql)->bindValue(':from_rbid', $_GET['from_rbid'])->queryAll();$param = ['res'=>$res];return $this->render('test',$param);}
使用Query对象只能查询数据库,但可以使用createCommand() 来实现dml操作
que
use Yii;public function actionTest2(){$db01 = Yii::$app->db01; // 连接数据库$res = (new Query())->from('rbid_change_info_test')->Where(['like','from_name','贝纳通'])->andWhere(['<','month','2021-01-30'])->limit(10)->all($db01);$param = [res=>$res,];return $this->render(test2,$param);}
createCommand()返回的是对象,all()返回的是数组
获取createCommand后,可以执行dml操作
导入
Query对象只能进行select查询操作
存在sql注入问题,可以通过占位符处理
不会有sql注入问题
即查询
in
#
用于拼接多个查询条件
在参数上和
where
的相同,但会跳过变量为空值的情况
where在查询变量值时,需要判断变量值是否为空,否则会出现查询空值
IS NULL
的情况
filterWhere无法查询空值的情况,不需要判断变量值是否为空
和where的使用方式一致
contoller层
use Yii;use yii\data\Pagination; use yii\db\Qurraery;public function actionTest(){$db01 = Yii::$app->db01; // 连接数据库$query = new Query();$res = $query->from('test_my.rbid_change_info_test');$totalCount = $res->count('*', $db01); //查询总记录数$pages = new Pagination(['totalCount' => $totalCount, //查询总记录数'pageSize' => 10, //每页记录数]);// 获取分页查询的数据$res = $res ->offset($pages->offset)->limit($pages->limit)->all($db01);$param = [res => $res, //结果集pages => $pages, // 分页对象totalCount => $totalCount,];return $this->render(test, $param);}
视图层view
$pages,'nextPageLabel' => '下一页','prevPageLabel' => '上一页','firstPageLabel' => '首页','lastPageLabel' => '尾页',]);}?>
use Yii;$db01 = Yii::$app->db01; // 连接数据库$transaction = $db01->beginTransaction();$res->createCommand($db01)->delete('test_my.t', 'from_rbid=:from_rbid', [':from_rbid' => 11])->execute();// $transaction->rollBack();$transaction->commit();
需要绑定model对象,自动进行validate()校验字段
如果不符合rules校验规则,则无法提交表单
推荐使用ActiveForm或者原生的html表单控件,ActiveForm控件不方便设置样式
= $form ->field($model, 'name', ['options' => ['class' => 'form-group row'], 'labelOptions' => ['label' => '姓名', 'class' => 'col-form-label mr-4']]) ->textInput(['autofocus' => true, 'placeholder' => '输入姓名', 'class' => 'form-control col-sm-2']) ?> = $form ->field($model, 'email', ['options' => ['class' => 'form-group row'], 'labelOptions' => ['label' => '邮箱', 'class' => 'col-form-label mr-4']]) ->textInput(['class' => 'form-control col-sm-2', 'placeholder' => '输入邮箱']) ?> = $form ->field($model, 'textArea', ['options' => ['class' => 'form-group row'], 'labelOptions' => ['label' => '留言', 'class' => 'col-form-label mr-4']]) ->textarea(['rows' => 8, 'class' => 'col-sm-4', 'placeholder' => '输入留言']) ?>
和html自己的表单控件一样,不会绑定model对象
类似使用
Input()
函数创建控件,只是可以用model
对象的字段值填充控件
比如使用ActiveRecord
获取表的记录字段值来填充控件,或者给ActiveRecord
对象赋值(ActiveRecord
继承Model
)
推荐用Url::to([''])
代替Url::current()
<form action="=Url::to(['form'])?>" class="input-group"> </form>
$this->params['breadcrumbs'][] = [label => 'Contact', url => ['/site/about']]; $this->params['breadcrumbs'][] = helllo; $this->params['breadcrumbs'][] = abcd;
$this->registerJsFile('@web/js/test/test.js');$this->registerCssFile('@web/css/test/test.css');
在控制台执行的脚本,需要放在
commands
目录下,但无法使用Xdebugaction方法的返回值return无法输出内容,内部使用echo可以在console中输出内容
来源地址:https://blog.csdn.net/qq_20051917/article/details/126594916
--结束END--
本文标题: 【php】yii2框架基础
本文链接: https://www.lsjlt.com/news/392305.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0