## Restful API接口实例
在Restful中一切都被认为是资源。每个资源有对应的URI标识
处理资源使用GET、POST、PUT、DELETE等http方法操作实现创建、读取、修改、删除的操作
### 用户类API:用户注册接口实现
实现功能:
1,PHP对MYSQL增删改查
2,实现注册、登录验证函数
3,简单封装返回JSON数据
步骤1:创建用户表 user
id / name / pwd / mobile / email / reg_time / update_time
步骤2:控制器
创建注册方法:
function registerAction(){
$user= $this->getRequest()->getPost("name",flase);
$pwd = $this->getRequest()->getPost("pwd",flase);
if(!user || $pwd){
echo json_encode(array("error"=>-1002, "errmsg"=>"用户名或密码不能为空"));
return false;
}
$model = new UserModel();
if($model->register(trim($name), trim($pwd))){
echo json_encode(array(
"error" => 0,
"errmsg"=>"",
"data"=>array("name"=>$user)
));
}else{
echo json_encode(array(
"error" => $model->errno,
"errmsg"=> $model->errmsg,
));
}
return true;
}
步骤3:Model
public function register($user,$pwd){
//1,检验user是否存在
$query = $this->_db->prepare("select count(*) as c from 'user' where 'name'=? ");
$query ->execute( array($user) );
$count= $query->fetchAll();
if($count[0]['c'] != 0){
$this->errno= -1005;
$this->errmsg="用户名已经存在";
return false;
}
if(strlen($pwd) <8){
$this->errno =-1006;
$this->errmsg = "密码不能少于8位";
return false;
}else{
$password = $this->psw_generate($pwd);
}
$query = $this->_db->prepare("insert into 'user'('id','name','pwd','reg_time') VALUES (null,?,?,?) ");
$ret = $query->execute(array($user,$password,date("Y-m-d H:i:s")));
if($ret){
$this->errno=-1006;
$this->errmsg="注册失败";
return false;
}
return true;
}
//用户密码MD5加密加盐
private funtion psw_generate($password){
$pwd = md5("salt-123123".$password);
return $pwd;
}
步骤4:自行调用接口调试