学习要点:
掌握如何获取数据
掌握如何把获取到的数据生成通信数据
访问方式:http://localhost/test/list.php?page=3&pagesize=1
或者http://localhost/test/list.php?format=xml
<?php
require_once "./response.php";
require_once "./db.php";
$page = isset($_GET['page'])?$_GET['page']:1;
$pagesize = isset($_GET['pagesize'])?$_GET['pagesize']:10;
if(!is_numeric($page) || !is_numeric($pagesize)){
return Response::show(401,'数据不合法');
}
//分页显示数据 偏移量
$offset = ($page-1)*$pagesize;
$sql = "select * from sys_role order by 'name' desc limit {$offset},{$pagesize}";
//捕获异常
try{
//连接数据库
$db = Db::getInstance()->connect();
}catch (EXception $e){
return Response::show(403,'数据库连接失败');
}
// 查询数据库
$recordset = $db->query($sql);
$recordset->setFetchMode(PDO::FETCH_ASSOC);
$result = $recordset->fetchAll();
if($result){
return Response::show(200,'首页数据获取成功',$result);
}else{
return Response::show(400,'首页数据获取失败');
}
包含的response.php文件
<?php
/**
* Created by PhpStorm.
* User: Administrator
*/
class Response
{
const TYPE = 'json';
/**
* 按综合方式去封装通信接口
* @param $code 状态码
* @param string $message 提示信息
* @param array $data 返回的数据
* @param string $type 获取的类型
*/
public static function show($code,$message='',$data=array(),$type=self::TYPE){
if(!is_numeric($code)){
return "";
}
$type = isset($_GET['format']) ? $_GET['format'] : self::TYPE;
$result = array(
'code'=>$code,
'message'=>$message,
'data'>$data
);
if($type == 'json'){
self::json($code,$message,$data);
exit;
}elseif($type == 'xml'){
self::xmlEncode($code,$message,$data);
exit;
}elseif($type == 'array'){
print_r($result);exit;
}else{
//todo
}
}
/**
* 按照json方式去封装接口数据方法
* @param $code 状态码
* @param string $message 提示消息
* @param array $data 返回的数据
* return string
*/
public static function json($code, $message = '', $data = array())
{
if (!is_numeric($code)) {
return "";
}
$result = array(
'code' => $code,
'message' => $message,
'data' => $data
);
echo json_encode($result);
exit;
}
/**
* php生成xml数据
*/
public static function xml()
{
header("Content-type:text/xml");
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= "<code>200</code>\n";
$xml .= "<message>数据返回成功</message>\n";
$xml .= "<data>\n";
$xml .= "<id>1</id>\n";
$xml .= "<name>caicai</name>\n";
$xml .= "<desc>this is a test</desc>\n";
$xml .= "</data>\n";
$xml .= "</root>";
echo $xml;
exit;
}
/**
* 按xml方式去封装通信接口
* @param $code 状态码
* @param string $message 提示信息
* @param array $data 返回的数据
*/
public static function xmlEncode($code,$message ='',$data=array()){
if(!is_numeric($code)){
return '';
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
header('Content-type:text/xml');
$xml = "<?xml version='1.0' encoding='UTF-8' ?>\n";
$xml .= "<root>";
$xml .= self::xmlToEncode($result);
$xml .= "</root>";
echo $xml;exit;
}
public static function xmlToEncode($data){
$xml = $attr = "";
foreach($data as $key=>$val){
if(is_numeric($key)){
$attr = "id= '{$key}'";
$key = "item ";
}
$xml .= "<{$key} {$attr}>";
$xml .= is_array($val) ? self::xmlToEncode($val) : $val;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
$data = array(
'id'=>1,
'name'=>'caicai',
// 'desc'=>array(1,3,5,'test'),
);
// Response::show(200,'数据返回成功',$data,'array');
包含的db.php文件
<?php
class Db
{
//拥有一个保护类实例的静态成员变量
static private $_instance;
static private $_connectSource;
const HOST='mysql:host=localhost;dbname=rht-test';
const USER='root';
const PASS='root';
//构造方法需要标记为非 public (防止外部使用new操作符创建对象),单例类不能在其他类中实例化,只能被自身实例化
private function __construct()
{
}
//拥有一个访问这个实例的公共静态方法
public static function getInstance()
{
//判断变量是否实例化
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
//防止克隆
private function __clone()
{
trigger_error("Can't clone object",E_USER_ERROR);
}
//连接数据库
public function connect()
{
self::$_connectSource = new PDO(Db::HOST,Db::USER,Db::PASS);
if(!self::$_connectSource){
throw new Exception("mysql connect error");
//die("mysql connect error".mysql_error());
}
self::$_connectSource->exec("set names utf8");
return self::$_connectSource;
}
}
// //连接数据库
// $db = Db::getInstance()->connect();
// // 查询数据库
// $recordset = $db->query("select * from sys_role");
// $recordset->setFetchMode(PDO::FETCH_ASSOC);
// $result = $recordset->fetchAll();
// echo "<pre>";
// var_dump($result);