APPインターフェースの開発 - 論文ホームインタフェース開発の読み静的キャッシュ

<?php
require_once "./response.php";
require_once "./db.php";
require_once "./file.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,'数据不合法');
}

$cache = new File;
$result = array();
//当缓存不存在时读取数据库数据 并将数据库数据放入缓存文件当中
if(!$result = $cache->cacheData('test'.$page.'_'.$pagesize)){//缓存文件名连接页码和每页显示条数,当缓存文件存在时,这里将读取缓存文件内容放入 $result 变量当中就不会进入 if的方法体当中,需要特别注意
	//分页显示数据  偏移量
	$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){
		$cache->cacheData('test'.$page.'_'.$pagesize,$result,1200);
	}

}

if($result){
	return Response::show(200,'首页数据获取成功',$result);
}else{
	return Response::show(400,'首页数据获取失败');
}

シングルトンクラスファイルデータベースパッケージ導入を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);

タイミング静的ファイル生成されたクラスファイルのfile.phpの紹介

<?php
class File
{
	private $_dir;
	const EXT = '.txt';

	public function __construct()
	{
		$this->_dir = dirname(__FILE__).'\files\/';
	}

	public function cacheData($path='',$value='',$cacheTime=0)
	{
		$filename = $this->_dir.$path.self::EXT;
		if($value !==''){

			//删除静态缓存文件
			if(is_null($value)){
				return @unlink($filename);				
			}
		
			//dirname() 返回路径中的目录部分 D:\phpstudy_pro\WWW\test\files
			$dir = dirname($filename);
			if(!is_dir($dir)){ //判读文件目录是否存在
				mkdir($dir,0777);
			}

			//格式化的字符串写入一个变量中 将缓存失效时间写入文件中
			$cacheTime = sprintf('%011d',$cacheTime);
			//file_put_contents() 写入文件内容
			return file_put_contents($filename,$cacheTime.json_encode($value));
		}

		//读取静态文件内容
		if(!is_file($filename)){//判断静态文件是否存在
			return false;
		}else{
			//file_get_contents()  读取文件内容
			$connects = file_get_contents($filename);
			//将缓失效时间截取
			$cacheTime = substr($connects,0,11);
			//获取缓存内容
			$value = substr($connects,11);

			//根据 生成文件时间+缓存文件时间 < 当前时间 条件成立则删除缓存文件
			if($cacheTime !=0 && $cacheTime+fileatime($filename) < time()){
				unlink($filename);
				return false;
			}
			return json_decode($value,true);
		}
	}		
}





// $file = new File;
// //测试数据
// $arr = array(
// 	'a'=>11111,
// 	'b'=>3333
// );

//写入缓存
// $file->cacheData('test',$arr,120);

// //读取文件内容
// echo "<pre>";
// var_dump($file->cacheData('test'));

//删除静态缓存文件
// var_dump($file->cacheData('test',NULL));

パッケージのクラスファイルの導入を持つXML、JSON通信フォーマット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');
公開された29元の記事 ウォンの賞賛0 ビュー323

おすすめ

転載: blog.csdn.net/weixin_39218464/article/details/104075089