濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > PHP常用的類封裝小結(jié)【4個(gè)工具類】

PHP常用的類封裝小結(jié)【4個(gè)工具類】

熱門標(biāo)簽:廣東廣州在怎么申請(qǐng)400電話 400電話蘭州申請(qǐng)請(qǐng) 余姚電話機(jī)器人 百度地圖怎樣標(biāo)注圖標(biāo) 電銷機(jī)器人問(wèn)門薩維品牌my 開發(fā)地圖標(biāo)注類網(wǎng)站 外呼系統(tǒng)能給企業(yè)帶來(lái)哪些好處 咸寧銷售電銷機(jī)器人系統(tǒng) 百度地圖標(biāo)注偏差

本文實(shí)例講述了PHP常用的類封裝。分享給大家供大家參考,具體如下:

這4個(gè)類分別是Mysql類、 分頁(yè)類、縮略圖類、上傳類。

Mysql類

?php
/**
 * Mysql類
 */
class Mysql{
  private static $link = null;//數(shù)據(jù)庫(kù)連接
  /**
   * 私有的構(gòu)造方法
   */
  private function __construct(){}
  /**
   * 連接數(shù)據(jù)庫(kù)
   * @return obj 資源對(duì)象
   */
  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語(yǔ)句
   * @param str $sql 查詢語(yǔ)句
   * @return obj   結(jié)果集對(duì)象
   */
  public static function query($sql){
    return self::conn()->query($sql);
  }
  /**
   * 獲取多行數(shù)據(jù)
   * @param str $sql 查詢語(yǔ)句
   * @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 查詢語(yǔ)句
   * @return arr   單行數(shù)據(jù)
   */
  public static function getRow($row){
    $res = self::query($sql);
    return $res->fetch_assoc();
  }
  /**
   * 獲取單個(gè)結(jié)果
   * @param str $sql 查詢語(yǔ)句
   * @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ù)庫(kù)連接
   * @return bool 是否關(guān)閉
   */
  public static function close(){
    return self::conn()->close();
  }
}
?>

分頁(yè)類

?php
/**
 * 分頁(yè)類
 * @author webbc
 */
class Page{
  private $num;//總的文章數(shù)
  private $cnt;//每頁(yè)顯示的文章數(shù)
  private $curr;//當(dāng)前的頁(yè)碼數(shù)
  private $p = 'page';//分頁(yè)參數(shù)名
  private $pageCnt = 5;//分欄總共顯示的頁(yè)數(shù)
  private $firstRow;//每頁(yè)的第一行數(shù)據(jù)
  private $pageIndex = array();//分頁(yè)信息
  /**
   * 構(gòu)造函數(shù)
   * @param int $num 總的文章數(shù)
   * @param int $cnt 每頁(yè)顯示的文章數(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();
  }
  /**
   * 分頁(yè)方法
   */
  private function getPage(){
    $page = ceil($this->num / $this->cnt);//總的頁(yè)數(shù)
    $left = max(1,$this->curr - floor($this->pageCnt/2));//計(jì)算最左邊頁(yè)碼
    $right = min($left + $this->pageCnt - 1 ,$page);//計(jì)算最右邊頁(yè)碼
    $left = max(1,$right - ($this->pageCnt - 1));//當(dāng)前頁(yè)碼往右靠,需要重新計(jì)算左邊頁(yè)面的值
    for($i=$left;$i=$right;$i++){
      if($i == 1){
        $index = '第1頁(yè)';
      }else if($i == $page){
        $index = '最后一頁(yè)';
      }else{
        $index = '第'.$i.'頁(yè)';
      }
      $_GET['page'] = $i;
      $this->pageIndex[$index] = http_build_query($_GET);
    }
  }
  /**
   * 返回分頁(yè)信息數(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 原圖的絕對(duì)路徑
   * @param integer $thumbWidth 縮略圖的寬
   * @param integer $thumbHeight 縮略圖的高
   */
  public function __construct($sourcePath,$thumbWidth=200,$thumbHeight=200){
    //獲取原圖的絕對(duì)路徑
    $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);
  }
  /**
   * 檢測(cè)原圖的擴(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);
  }
  /**
   * 檢測(cè)文件擴(kuò)展名是否合法
   * @param str $filename 文件名
   * @return bool 文件擴(kuò)展名是否合法
   */
  private function checkExt($filename){
    $ext = $this->getExt($filename);
    return in_array($ext,$this->allowExt);
  }
  /**
   * 檢測(cè)文件大小是否超過(guò)限制
   * @param int size 文件大小
   * @return bool 文件大小是否超過(guò)限制
   */
  public function checkSize($size){
    return $size  $this->maxSize * 1024 * 1024;
  }
  /**
   * 隨機(jī)的文件名
   * @param int $len 隨機(jī)文件名的長(zhǎng)度
   * @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 "沒(méi)有上傳文件";
      return;
    }
    $info = $this->getInfo($flag);
    if(!$this->checkExt($info['name'])){
      echo "不支持的文件類型";
      return;
    }
    if(!$this->checkSize($info['size'])){
      echo "文件大小超過(guò)限制";
      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ù)庫(kù)操作入門教程》、《php+mysqli數(shù)據(jù)庫(kù)程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • PHP基于MySQLI函數(shù)封裝的數(shù)據(jù)庫(kù)連接工具類【定義與用法】
  • 常用PHP封裝分頁(yè)工具類
  • php封裝的驗(yàn)證碼工具類完整實(shí)例
  • PHP封裝的驗(yàn)證碼工具類定義與用法示例
  • php封裝的pdo數(shù)據(jù)庫(kù)操作工具類與用法示例
  • PHP抓取、分析國(guó)內(nèi)視頻網(wǎng)站的視頻信息工具類
  • PHP常用工具類大全附全部代碼下載
  • PHP實(shí)現(xiàn)基于面向?qū)ο蟮膍ysqli擴(kuò)展庫(kù)增刪改查操作工具類
  • PHP實(shí)現(xiàn)可添加水印與生成縮略圖的圖片處理工具類
  • php實(shí)現(xiàn)網(wǎng)頁(yè)緩存的工具類分享

標(biāo)簽:銅陵 衡陽(yáng) 鷹潭 重慶 十堰 巴彥淖爾 臨沂 麗江

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP常用的類封裝小結(jié)【4個(gè)工具類】》,本文關(guān)鍵詞  PHP,常用的,常,用的,類,封裝,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《PHP常用的類封裝小結(jié)【4個(gè)工具類】》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于PHP常用的類封裝小結(jié)【4個(gè)工具類】的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    湛江市| 汕尾市| 门头沟区| 美姑县| 娱乐| 丽江市| 隆尧县| 民县| 五大连池市| 神池县| 漾濞| 西乌| 郧西县| 涟源市| 玉树县| 涞水县| 池州市| 滦南县| 玉门市| 凯里市| 潼关县| 鄂伦春自治旗| 阜康市| 仁寿县| 钦州市| 神木县| 新丰县| 临汾市| 绥阳县| 五家渠市| 德庆县| 广汉市| 格尔木市| 溧水县| 新化县| 新和县| 永泰县| 于都县| 白河县| 共和县| 柳河县|