单例模式链接数据库

//db.php


/**

* 单例链接数据库

* */

classDb {

static private$_instance;

static private$_connectSource;

private$_dbConfig=array(

'host'=>'127.0.0.1',

'user'=>'root',

'password'=>'',

'database'=>'video',

);

private function__construct() {

}

static public functiongetInstance() {

if(!(self::$_instanceinstanceof self)) {

self::$_instance=new self();

}

return self::$_instance;

}

public functionconnect() {

if(!self::$_connectSource) {

self::$_connectSource= @mysql_connect($this->_dbConfig['host'],$this->_dbConfig['user'],$this->_dbConfig['password']);

if(!self::$_connectSource) {

throw newException('mysql connect error '. mysql_error());

//die('mysql connect error' . mysql_error());

}

mysql_select_db($this->_dbConfig['database'],self::$_connectSource);

mysql_query("set names UTF8",self::$_connectSource);

}

return self::$_connectSource;

}

}

//response.php


classResponse {

constJSON="json";

/**

* 按综合方式输出通信数据

*@paraminteger $code 状态码

*@paramstring $message 提示信息

*@paramarray $data 数据

*@paramstring $type 数据类型

* return string

*/

public static functionshow($code,$message='',$data=array(),$type=self::JSON) {

if(!is_numeric($code)) {

return'';

}

if(in_array($_GET['format'],array('json','xml','jsonp'))){

$type='json';

}

//    $type = isset($_GET['format']) ? $_GET['format'] : self::JSON;

$result=array(

'code'=>$code,

'message'=>$message,

'data'=>$data,

);

if($type=='json') {

self::json($code,$message,$data);

exit;

}elseif($type=='array') {

var_dump($result);

}elseif($type=='xml') {

self::xmlEncode($code,$message,$data);

exit;

}else{

//TODO

}

}

/**

* 按json方式输出通信数据

*@paraminteger $code 状态码

*@paramstring $message 提示信息

*@paramarray $data 数据

* return string

*/

public static functionjson($code,$message='',$data=array()) {

if(!is_numeric($code)) {

return'';

}

$result=array(

'code'=>$code,

'message'=>$message,

'data'=>$data

);

echojson_encode($result);

exit;

}

/**

* 按xml方式输出通信数据

*@paraminteger $code 状态码

*@paramstring $message 提示信息

*@paramarray $data 数据

* return string

*/

public static functionxmlEncode($code,$message,$data=array()) {

if(!is_numeric($code)) {

return'';

}

$result=array(

'code'=>$code,

'message'=>$message,

'data'=>$data,

);

header("Content-Type:text/xml");

$xml="\n";

$xml.="\n";

$xml.=self::xmlToEncode($result);

$xml.="";

echo$xml;

}

/**

* 转换成xml数据返回

* */

public static functionxmlToEncode($data) {

$xml=$attr="";

foreach($dataas$key=>$value) {

if(is_numeric($key)) {

$attr=" id='{$key}'";

$key="item";

}

$xml.="<{$key}{$attr}>";

$xml.= is_array($value) ?self::xmlToEncode($value) :$value;

$xml.="\n";

}

return$xml;

}

}

//list.php



// http://app.com/list.php?page-=1&pagesize=12

require_once('./response.php');

require_once('./file.php');

$file=newFile();

$data=$file->cacheData('index_cron_cahce');

if($data) {

returnResponse::show(200,'首页数据获取成功',$data);

}else{

returnResponse::show(400,'首页数据获取失败',$data);

}

exit;

require_once('./db.php');

require_once('./file.php');

$page=isset($_GET['page']) ?$_GET['page'] :1;

$pageSize=isset($_GET['pagesize']) ?$_GET['pagesize'] :6;

if(!is_numeric($page) || !is_numeric($pageSize)) {

returnResponse::show(401,'数据不合法');

}

$offset= ($page-1) *$pageSize;

$sql="select*from video where status = 1 order by orderby desc limit ".$offset." , ".$pageSize;

$cache=newFile();

$videos=array();

if(!$videos=$cache->cacheData('index_mk_cache'.$page.'-'.$pageSize)) {

echo1;exit;

try{

$connect= Db::getInstance()->connect();

}catch(Exception$e) {

// $e->getMessage();

returnResponse::show(403,'数据库链接失败');

}

$result= mysql_query($sql,$connect);

while($video= mysql_fetch_assoc($result)) {

$videos[] =$video;

}

if($videos) {

$cache->cacheData('index_mk_cache'.$page.'-'.$pageSize,$videos,1200);

}

}

if($videos) {

returnResponse::show(200,'首页数据获取成功',$videos);

}else{

returnResponse::show(400,'首页数据获取失败',$videos);

}

//缓存文件



/**

* 生成缓存文件、删除、读取缓存的操作封装

*

* */

classFile {

private$_dir;

constEXT='.txt';

/**

* 初始化文件存储位置

* */

public function__construct() {

$this->_dir= dirname(__FILE__) .'/files/';

}

/**

* param $key 缓存文件名称

* param $value 缓存文件的值

* */

public functioncacheData($key,$value='') {

$filename=$this->_dir.$key.self::EXT;

if($value!=='') {// 将value值写入缓存

if(is_null($value)) {

return@unlink($filename);

}

$dir= dirname($filename);

if(!is_dir($dir)) {

mkdir($dir,0777);

}

returnfile_put_contents($filename,json_encode($value));

}

if(!is_file($filename)) {

return FALSE;

}

/*

* 定时删除缓存文件

* */

//    $contents = file_get_contents($filename);

//    $cacheTime = (int)substr($contents, 0 ,11);

//    $value = substr($contents, 11);

//    if($cacheTime !=0 && ($cacheTime + filemtime($filename) < time())) {

//      unlink($filename);

//      return FALSE;

//    }

returnjson_decode(file_get_contents($filename),true);

}

}





/**

* 生成缓存文件、删除、读取缓存的操作封装

*

* */

classFile {

private$_dir;

constEXT='.txt';

/**

* 初始化文件存储位置

* */

public function__construct() {

$this->_dir= dirname(__FILE__) .'/files/';

}

/**

* param $key 缓存文件名称

* param $value 缓存文件的值

* */

public functioncacheData($key,$value='') {

$filename=$this->_dir.$key.self::EXT;

if($value!=='') {// 将value值写入缓存

if(is_null($value)) {

return@unlink($filename);

}

$dir= dirname($filename);

if(!is_dir($dir)) {

mkdir($dir,0777);

}

returnfile_put_contents($filename,json_encode($value));

}

if(!is_file($filename)) {

return FALSE;

}

/*

* 定时删除缓存文件

* */

//    $contents = file_get_contents($filename);

//    $cacheTime = (int)substr($contents, 0 ,11);

//    $value = substr($contents, 11);

//    if($cacheTime !=0 && ($cacheTime + filemtime($filename) < time())) {

//      unlink($filename);

//      return FALSE;

//    }

returnjson_decode(file_get_contents($filename),true);

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,253评论 19 139
  • 如何单例模式链接数据库 =================== 1.单例模式 单例模式主要是三点:隐藏掉(priv...
    MadLife程序员阅读 1,900评论 0 3
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,838评论 18 399
  • 闻讯同学徐辉的著作出版,订购,散文集,《淌过诗人的河流》。 收到老同学岳阳快递的《淌过诗人的河流》,万分亲切!然,...
    传频阅读 386评论 0 2
  • 静态缓存 要使用静态缓存功能,需要开启HTML_CACHE_ON参数,并且使用HTML_CACHE_RULES配置...
    栾呱呱阅读 2,310评论 0 6