單例模式三大原則:
1. 構造函數(shù)需要標記為非public(防止外部使用new操作符創(chuàng)建對象)听皿,單例類不能在其他類中實例化选侨,
只能被其自身實例化
2. 擁有一個保存類的實例的靜態(tài)成員變量 $_instance
3. 擁有一個訪問這個實例的公共的靜態(tài)方法
例:
<?php
class Db {
static private $_instance;
static private $_connectSource;
private $_dbConfig = array{
'host' => '127.0.0.1',
'user' => 'root',
'password' => ' ',
'database' => 'video',
}
private function _construct() {
}
static public function getInstance() {
//先判斷這個實例是否存在牵舱,不存在才創(chuàng)建
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
public function connect() {
//如果資源不存在再創(chuàng)建
if(!self::$_connectSource){
self::$_connectSource = mysql_connect($this->_dbConfig['host'],
$this->_dbConfig['user'], $this->_dbConfig['password']);
if(!self::$_connectSource) {
//直接這樣如果連接失敗易給客戶端造成崩潰,所以最好這里拋出異常
//die('mysql connect error' . mysql_error());
throw new Exception('mysql connect error' . mysql_error());
}
mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
mysql_query("set names UTF8", self::$_connectSource);
}
return self::$_connectSource;
}
}
//調用方法
$connect = Db::getInstance()->connect();
$sql = "select * from video";
$result = mysql_query($sql,$connect);
echo mysql_num_rows($result);//輸出結果集中的個數(shù)
var_dump($result);
?>
方案一:讀取數(shù)據(jù)庫方式開發(fā)首頁接口
從數(shù)據(jù)庫獲取信息 -> 封裝 -> 生成數(shù)據(jù)接口
應用場景:數(shù)據(jù)時效性比較高的系統(tǒng)
方案二:讀取緩存方式開發(fā)首頁接口
從數(shù)據(jù)庫獲取信息 -> 封裝 -> 返回數(shù)據(jù)
-> 緩存
再次請求 -> 緩存 -> 封裝 -> 返回數(shù)據(jù)
方案三:定時讀取緩存方式開發(fā)首頁接口
數(shù)據(jù)庫 -> crontab -> 緩存
http請求 -> 緩存 -> 封裝并返回數(shù)據(jù)
方案一流程:
http請求 -> 服務器 -> 查詢數(shù)據(jù) -> 返回數(shù)據(jù)
例:
<?php
//接口示例:http://app.com/list.php?page=1&pagesize=12
require_once('./response.php');//引入類文件
require_once('./Db.php');
$page = isset($_GET['page']) ? $_GET['page'] : 1; //isset判斷是否存在
$pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 1;
//如果不是數(shù)字眯漩,則返回自定義錯誤信息
if(!is_numeric($page) || !is_numeric($pageSize)) {
return Response::show(401,'數(shù)據(jù)不合法');//自定義狀態(tài)碼
}
$offset = ($page - 1) * $pageSize;//起始頁
//數(shù)據(jù)庫中字段status=1,orderby倒序的片仿,limit 0,6設置起始頁0中的6條數(shù)據(jù)
$sql = "select * from video where status = 1 order by orderby desc limit ". $offset ."," .$pageSize;
//接收異常
try {
$connect = Db::getInstance()->connect();
}catch(Exception $e) {
return Response::show(403,'數(shù)據(jù)庫連接失敗');
}
$result = mysql_query($sql, $connect);//是一個結果集
$videos = array();
//遍歷結果集
while($video = mysql_fetch_assoc($result)) {
$videos[] = $video;
}
if($videos) {
//直接調用生成接口數(shù)據(jù)方法返回給客戶端
return Response::show(200,'首頁數(shù)據(jù)獲取成功',$videos);
}else {
return Response::show(400,'首頁數(shù)據(jù)獲取失敗',$videos);
}
?>
基本參數(shù)傳遞方式和獲取方法:
方式 獲取
get $_GET
post $_POST
header頭 $_SERVER
注:$_SERVER 是一個包含了諸如頭信息(header)统锤、路徑(path)、以及腳本位置(script locations)等信息的數(shù)組
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者