本文實(shí)例講述了PHP常用的類封裝。分享給大家供大家參考,具體如下:
這4個(gè)類分別是Mysql類、 分頁類、縮略圖類、上傳類。
Mysql類
?php /** * Mysql類 */ class Mysql{ private static $link = null;//數(shù)據(jù)庫連接 /** * 私有的構(gòu)造方法 */ private function __construct(){} /** * 連接數(shù)據(jù)庫 * @return obj 資源對象 */ private static function conn(){ if(self::$link === null){ $cfg = require './config.php'; self::$link = new Mysqli($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']); self::query("set names ".$cfg['charset']);//設(shè)置字符集 } return self::$link; } /** * 執(zhí)行一條sql語句 * @param str $sql 查詢語句 * @return obj 結(jié)果集對象 */ public static function query($sql){ return self::conn()->query($sql); } /** * 獲取多行數(shù)據(jù) * @param str $sql 查詢語句 * @return arr 多行數(shù)據(jù) */ public static function getAll($sql){ $data = array(); $res = self::query($sql); while($row = $res->fetch_assoc()){ $data[] = $row; } return $data; } /** * 獲取一行數(shù)據(jù) * @param str $row 查詢語句 * @return arr 單行數(shù)據(jù) */ public static function getRow($row){ $res = self::query($sql); return $res->fetch_assoc(); } /** * 獲取單個(gè)結(jié)果 * @param str $sql 查詢語句 * @return str 單個(gè)結(jié)果 */ public static function getOne($sql){ $res = self::query($sql); $data = $res->fetch_row(); return $data[0]; } /** * 插入/更新數(shù)據(jù) * @param str $table 表名 * @param arr $data 插入/更新的數(shù)據(jù) * @param str $act insert/update * @param str $where 更新條件 * @return bool 插入/更新是否成功 */ public static function exec($table,$data,$act='insert',$where='0'){ //插入操作 if($act == 'insert'){ $sql = 'insert into '.$table; $sql .= ' ('.implode(',',array_keys($data)).')'; $sql .= " values ('".implode("','",array_values($data))."')"; }else if($act == 'update'){ $sql = 'update '.$table.' set '; foreach ($data as $k => $v) { $sql .= $k.'='."'$v',"; } $sql = rtrim($sql,','); $sql .= ' where 1 and '.$where; } return self::query($sql); } /** * 獲取最近一次插入的主鍵值 * @return int 主鍵 */ public static function getLastId(){ return self::conn()->insert_id; } /** * 獲取最近一次操作影響的行數(shù) * @return int 影響的行數(shù) */ public static function getAffectedRows(){ return self::conn()->affected_rows; } /** * 關(guān)閉數(shù)據(jù)庫連接 * @return bool 是否關(guān)閉 */ public static function close(){ return self::conn()->close(); } } ?>
分頁類
?php /** * 分頁類 * @author webbc */ class Page{ private $num;//總的文章數(shù) private $cnt;//每頁顯示的文章數(shù) private $curr;//當(dāng)前的頁碼數(shù) private $p = 'page';//分頁參數(shù)名 private $pageCnt = 5;//分欄總共顯示的頁數(shù) private $firstRow;//每頁的第一行數(shù)據(jù) private $pageIndex = array();//分頁信息 /** * 構(gòu)造函數(shù) * @param int $num 總的文章數(shù) * @param int $cnt 每頁顯示的文章數(shù) */ public function __construct($num,$cnt=10){ $this->num = $num; $this->cnt = $cnt; $this->curr = empty($_GET[$this->p]) ? 1 : intval($_GET[$this->p]); $this->curr = $this->curr > 0 ? $this->curr : 1; $this->firstRow = $this->cnt * ($this->curr - 1); $this->getPage(); } /** * 分頁方法 */ private function getPage(){ $page = ceil($this->num / $this->cnt);//總的頁數(shù) $left = max(1,$this->curr - floor($this->pageCnt/2));//計(jì)算最左邊頁碼 $right = min($left + $this->pageCnt - 1 ,$page);//計(jì)算最右邊頁碼 $left = max(1,$right - ($this->pageCnt - 1));//當(dāng)前頁碼往右靠,需要重新計(jì)算左邊頁面的值 for($i=$left;$i=$right;$i++){ if($i == 1){ $index = '第1頁'; }else if($i == $page){ $index = '最后一頁'; }else{ $index = '第'.$i.'頁'; } $_GET['page'] = $i; $this->pageIndex[$index] = http_build_query($_GET); } } /** * 返回分頁信息數(shù)據(jù) * @return [type] [description] */ public function show(){ return $this->pageIndex; } } ?>
縮略圖類
?php /** * 縮略圖類 * @author webbc */ class Thumb{ private $thumbWidth;//縮略圖的寬 private $thumbHeight;//縮略圖的高 private $thumbPath;//縮略圖保存的路徑 private $sourcePath;//原圖的路徑 private $sourceWidth;//原圖的寬度 private $sourceHeight;//原圖的高度 private $sourceType;//原圖的圖片類型 /** * 構(gòu)造函數(shù) * @param str $sourcePath 原圖的絕對路徑 * @param integer $thumbWidth 縮略圖的寬 * @param integer $thumbHeight 縮略圖的高 */ public function __construct($sourcePath,$thumbWidth=200,$thumbHeight=200){ //獲取原圖的絕對路徑 $this->sourcePath = $sourcePath; //獲取縮略圖的大小 $this->thumbWidth = $thumbWidth; $this->thumbHeight = $thumbHeight; $this->thumbPath = $this->getThumbPath(); //計(jì)算大圖的大小 list($this->sourceWidth,$this->sourceHeight,$this->sourceType) = getimagesize($this->sourcePath); } /** * 確定縮略圖保存的路徑 * @return [type] [description] */ private function getThumbPath(){ $ext = $this->getExt(); $filename = basename($this->sourcePath,'.'.$ext).'_thumb'.'.'.$ext; return $thumbPath = __DIR__.'/'.$filename; } /** * 獲取原圖的擴(kuò)展名 * @return str 擴(kuò)展名 */ private function getExt(){ return pathinfo($this->sourcePath,PATHINFO_EXTENSION); } /** * 檢測原圖的擴(kuò)展名是否合法,并返回相應(yīng)類型 * @return bool/str 原圖的類型 */ public function getType(){ $typeArr = array( 1 => 'gif', 2 => 'jpeg', 3 => 'png', 15 => 'wbmp' ); if(!in_array($this->sourceType, array_keys($typeArr))){ return false; } return $typeArr[$this->sourceType]; } /** * 按照縮略圖大小,計(jì)算大圖的縮放比例 * @return float 縮放比例 */ public function calculateRate(){ return min($this->thumbWidth / $this->sourceWidth,$this->thumbHeight / $this->sourceHeight); } /** * 計(jì)算大圖按照縮放比例后,最終的圖像大小 * @param float $rate 縮放比例 * @return arr 縮放后的圖片大小 */ public function getImageSizeByRate($rate){ $width = $this->sourceWidth * $rate; $height = $this->sourceHeight * $rate; return array('w'=>$width,'h'=>$height); } /** * 保存成文件 * @return [type] [description] */ public function saveFile($image){ $method = "image".$this->getType(); $method($image,$this->thumbPath); } /** * 進(jìn)行繪畫操作 * @return [type] [description] */ public function draw(){ if(!($type = $this->getType())){ echo "文件類型不支持"; return ; } //創(chuàng)建大圖和小圖的畫布 $method = "imagecreatefrom".$type; $bigCanvas = $method($this->sourcePath); $smallCanvas = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight); //創(chuàng)建白色畫筆,并給小圖畫布填充背景 $white = imagecolorallocate($smallCanvas, 255, 255, 255); imagefill($smallCanvas, 0, 0, $white); //計(jì)算大圖的縮放比例 $rate = $this->calculateRate(); //計(jì)算大圖縮放后的大小信息 $info = $this->getImageSizeByRate($rate); //進(jìn)行縮放 imagecopyresampled($smallCanvas, $bigCanvas, ($this->thumbWidth - $info['w']) / 2 , ($this->thumbHeight - $info['h']) / 2, 0, 0, $info['w'], $info['h'], $this->sourceWidth, $this->sourceHeight); //保存成文件 $this->saveFile($smallCanvas); //銷毀畫布 imagedestroy($bigCanvas); imagedestroy($smallCanvas); } } ?>
上傳類
meta charset="utf8"/> ?php /** * 文件上傳類 * @author webbc */ class Upload{ private $allowExt = array('gif','jpg','jpeg','bmp','png','swf');//限制文件上傳的后綴名 private $maxSize = 1;//限制最大文件上傳1M /** * 獲取文件的信息 * @param str $flag 上傳文件的標(biāo)識(shí) * @return arr 上傳文件的信息數(shù)組 */ public function getInfo($flag){ return $_FILES[$flag]; } /** * 獲取文件的擴(kuò)展名 * @param str $filename 文件名 * @return str 文件擴(kuò)展名 */ public function getExt($filename){ return pathinfo($filename,PATHINFO_EXTENSION); } /** * 檢測文件擴(kuò)展名是否合法 * @param str $filename 文件名 * @return bool 文件擴(kuò)展名是否合法 */ private function checkExt($filename){ $ext = $this->getExt($filename); return in_array($ext,$this->allowExt); } /** * 檢測文件大小是否超過限制 * @param int size 文件大小 * @return bool 文件大小是否超過限制 */ public function checkSize($size){ return $size $this->maxSize * 1024 * 1024; } /** * 隨機(jī)的文件名 * @param int $len 隨機(jī)文件名的長度 * @return str 隨機(jī)字符串 */ public function randName($len=6){ return substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ234565789'),0,$len); } /** * 創(chuàng)建文件上傳到的路徑 * @return str 文件上傳的路徑 */ public function createDir(){ $dir = './upload/'.date('Y/m/d',time()); if(is_dir($dir) || mkdir($dir,0777,true)){ return $dir; } } /** * 文件上傳 * @param str $flag 文件上傳標(biāo)識(shí) * @return arr 文件上傳信息 */ public function uploadFile($flag){ if($_FILES[$flag]['name'] === '' || $_FILES[$flag]['error'] !== 0){ echo "沒有上傳文件"; return; } $info = $this->getInfo($flag); if(!$this->checkExt($info['name'])){ echo "不支持的文件類型"; return; } if(!$this->checkSize($info['size'])){ echo "文件大小超過限制"; return; } $filename = $this->randName().'.'.$this->getExt($info['name']); $dir = $this->createDir(); if(!move_uploaded_file($info['tmp_name'], $dir.'/'.$filename)){ echo "文件上傳失敗"; }else{ return array('filename'=>$filename,'dir'=>$dir); } } } ?>
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+mysql數(shù)據(jù)庫操作入門教程》、《php+mysqli數(shù)據(jù)庫程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:銅陵 衡陽 鷹潭 重慶 十堰 巴彥淖爾 臨沂 麗江
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP常用的類封裝小結(jié)【4個(gè)工具類】》,本文關(guān)鍵詞 PHP,常用的,常,用的,類,封裝,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。