tp5+小程序开发笔记(一)tp5路由/传参/验证

AOP编程思想--面向切面编程

tp5路由:

(设置了路由后pathinfo失效)

Route::rule('路由表达式','路由地址','请求类型','路由参数(数组)','变量规则(数组)');

请求类型:get  post   delete  put   any(默认所有)

use think\Route;
Route::rule('test','api/Test/index','GET');
Route::rule('test','api/Test/index','GET | POST');

路由中传递参数

get方式

Route::rule('test/:id','api/Test/index','GET');
public function index($id,$name)
{
echo "id=".$id."name=".$name;
}

访问方式:http://localhost/xcx_shop/public/index.php/test/11?name=xx

post方式

Route::post('test/:id','index/test/index');

 

获取参数

1.

use think\Request;
param不区分参数来源
获取单个传过来的参数
$id = Request::instance()->param('id');

获取所有传过来的参数
$all = Request::instance()->param();

获取get方式传过来的参数
$all = Request::instance()->get();

获取路径中传过来的参数 
$all = Request::instance()->route();

获取post方式传过来的参数 
$all = Request::instance()->post();

....

2.助手函数

input('param.');

3.依赖注入

use think\Request;
public function test(Request $request)
{
$all = $request->param();
}
//$request  不需要关注从哪里来的 

 

 

验证

1.独立验证

$validate = new Validate([
'pwd' => 'require',
'new_pwd' => 'require',
'confirm_pwd' => 'require|confirm:new_pwd'
],[
'pwd.require' => '请输入原始密码',
'new_pwd.require' => '请输入新密码',
'confirm_pwd.require' => '请重复新密码',
'confirm_pwd.confirm' => '确认密码与新密码不一致'
]
);
if (!$validate->check($data)) {
return ['valid'=> 0,'msg'=>$validate->getError()];
}
//原始密码是否正确
$userInfo = $this->where('pwd',$data['pwd'])->where('id',session('admin_id'))->find();
if(!$userInfo){
return ['valid'=>0, 'msg'=>'原始密码不正确'];
}
//修改密码
// save方法第二个参数为更新条件
$res = $this->save([
'pwd' =>$data['new_pwd'],
],[$this->pk => session('admin_id')]);
if($res){
return ['valid'=>1, 'msg'=>'密码修改成功'];
}else{
return ['valid'=>0, 'msg'=>'密码修改失败'];
}

2.验证器

新建TestValideta.php

<?php
namespace app\api\validate;
use think\validate;
class TestValidate extends validate
{
    protected $rule =[
    	'pwd' => 'require',
    	'new_pwd' => 'require',
    	'confirm_pwd' => 'require|confirm:new_pwd'
    ];
    protected function isInt($value,$rule='',$data,$field='')
   {
   	if(is_number($value) && is_int($value +0) && ($value +0)>0){
   		return true;
   	}else{
   		return $field."必须是正整数";
   	}

   }

}

使用:
$validate = new TestValidate();
$result = $validate ->batch()->check($data);


3.自定义验证规则(如上)

protected function isInt($value,$rule='',$data,$field='')
   	{
   		if(is_number($value) && is_int($value +0) && ($value +0)>0){
   			return true;
   		}else{
   			return $field."必须是正整数";
   		}

   	}

查看更多文章请访问:https://www.wangmingchang.com/


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员子枫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值