美文网首页
单例模式链接数据库

单例模式链接数据库

作者: 刚_dbac | 来源:发表于2017-08-08 18:04 被阅读0次

//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);

}

}

相关文章

  • 如何单例模式链接数据库

    如何单例模式链接数据库 =================== 1.单例模式 单例模式主要是三点:隐藏掉(priv...

  • 单例模式链接数据库

    //db.php /** * 单例链接数据库 * */ classDb { static private$_ins...

  • python的单例模式 连接mongo数据库

    数据库的增删改查都先要链接数据库,不然到处都在链接数据库,很烂费资源和性能,今天就把mongo的连接池的单例模式封...

  • 单例模式和工厂模式

    单例模式 数据库连接可以使用单例模式。。。单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便...

  • 你说你熟悉java设计模式,那单例模式的这几种创建方式你都知道吗

    单例模式使用案例 数据库的连接池; Spring中的Bean默认也是单例的; 单例模式的特性 将构造函数私有化 在...

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • 设计模式

    单例模式模式工厂模式模式策略者模式适配器模式观察者模式 单例模式 php的应用主要在于数据库应用: 一个应用中会存...

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • php 设计模式之单类模式

    单例模式:一个类只能产生一个对象,如果希望在系统中某个类(比如链接数据库的类)的对象只能存在一个,就选用单类模式。...

  • PHP中的设计模式

    单例模式 项目层面的单例应用,实例化多个数据库模型 工厂模式 传递不同的参数,获得不同的对象 策略模式 传递不同的...

网友评论

      本文标题:单例模式链接数据库

      本文链接:https://www.haomeiwen.com/subject/tutxrxtx.html