当前位置:Gxlcms > PHP教程 > PHP常用的类封装小结【4个工具类】

PHP常用的类封装小结【4个工具类】

时间:2021-07-01 10:21:17 帮助过:82人阅读

本文实例讲述了PHP常用的类封装。分享给大家供大家参考,具体如下:

这4个类分别是Mysql类、 分页类、缩略图类、上传类。

Mysql类

  1. <?php
  2. /**
  3. * Mysql类
  4. */
  5. class Mysql{
  6. private static $link = null;//数据库连接
  7. /**
  8. * 私有的构造方法
  9. */
  10. private function __construct(){}
  11. /**
  12. * 连接数据库
  13. * @return obj 资源对象
  14. */
  15. private static function conn(){
  16. if(self::$link === null){
  17. $cfg = require './config.php';
  18. self::$link = new Mysqli($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']);
  19. self::query("set names ".$cfg['charset']);//设置字符集
  20. }
  21. return self::$link;
  22. }
  23. /**
  24. * 执行一条sql语句
  25. * @param str $sql 查询语句
  26. * @return obj 结果集对象
  27. */
  28. public static function query($sql){
  29. return self::conn()->query($sql);
  30. }
  31. /**
  32. * 获取多行数据
  33. * @param str $sql 查询语句
  34. * @return arr 多行数据
  35. */
  36. public static function getAll($sql){
  37. $data = array();
  38. $res = self::query($sql);
  39. while($row = $res->fetch_assoc()){
  40. $data[] = $row;
  41. }
  42. return $data;
  43. }
  44. /**
  45. * 获取一行数据
  46. * @param str $row 查询语句
  47. * @return arr 单行数据
  48. */
  49. public static function getRow($row){
  50. $res = self::query($sql);
  51. return $res->fetch_assoc();
  52. }
  53. /**
  54. * 获取单个结果
  55. * @param str $sql 查询语句
  56. * @return str 单个结果
  57. */
  58. public static function getOne($sql){
  59. $res = self::query($sql);
  60. $data = $res->fetch_row();
  61. return $data[0];
  62. }
  63. /**
  64. * 插入/更新数据
  65. * @param str $table 表名
  66. * @param arr $data 插入/更新的数据
  67. * @param str $act insert/update
  68. * @param str $where 更新条件
  69. * @return bool 插入/更新是否成功
  70. */
  71. public static function exec($table,$data,$act='insert',$where='0'){
  72. //插入操作
  73. if($act == 'insert'){
  74. $sql = 'insert into '.$table;
  75. $sql .= ' ('.implode(',',array_keys($data)).')';
  76. $sql .= " values ('".implode("','",array_values($data))."')";
  77. }else if($act == 'update'){
  78. $sql = 'update '.$table.' set ';
  79. foreach ($data as $k => $v) {
  80. $sql .= $k.'='."'$v',";
  81. }
  82. $sql = rtrim($sql,',');
  83. $sql .= ' where 1 and '.$where;
  84. }
  85. return self::query($sql);
  86. }
  87. /**
  88. * 获取最近一次插入的主键值
  89. * @return int 主键
  90. */
  91. public static function getLastId(){
  92. return self::conn()->insert_id;
  93. }
  94. /**
  95. * 获取最近一次操作影响的行数
  96. * @return int 影响的行数
  97. */
  98. public static function getAffectedRows(){
  99. return self::conn()->affected_rows;
  100. }
  101. /**
  102. * 关闭数据库连接
  103. * @return bool 是否关闭
  104. */
  105. public static function close(){
  106. return self::conn()->close();
  107. }
  108. }
  109. ?>

分页类

  1. <?php
  2. /**
  3. * 分页类
  4. * @author webbc
  5. */
  6. class Page{
  7. private $num;//总的文章数
  8. private $cnt;//每页显示的文章数
  9. private $curr;//当前的页码数
  10. private $p = 'page';//分页参数名
  11. private $pageCnt = 5;//分栏总共显示的页数
  12. private $firstRow;//每页的第一行数据
  13. private $pageIndex = array();//分页信息
  14. /**
  15. * 构造函数
  16. * @param int $num 总的文章数
  17. * @param int $cnt 每页显示的文章数
  18. */
  19. public function __construct($num,$cnt=10){
  20. $this->num = $num;
  21. $this->cnt = $cnt;
  22. $this->curr = empty($_GET[$this->p]) ? 1 : intval($_GET[$this->p]);
  23. $this->curr = $this->curr > 0 ? $this->curr : 1;
  24. $this->firstRow = $this->cnt * ($this->curr - 1);
  25. $this->getPage();
  26. }
  27. /**
  28. * 分页方法
  29. */
  30. private function getPage(){
  31. $page = ceil($this->num / $this->cnt);//总的页数
  32. $left = max(1,$this->curr - floor($this->pageCnt/2));//计算最左边页码
  33. $right = min($left + $this->pageCnt - 1 ,$page);//计算最右边页码
  34. $left = max(1,$right - ($this->pageCnt - 1));//当前页码往右靠,需要重新计算左边页面的值
  35. for($i=$left;$i<=$right;$i++){
  36. if($i == 1){
  37. $index = '第1页';
  38. }else if($i == $page){
  39. $index = '最后一页';
  40. }else{
  41. $index = '第'.$i.'页';
  42. }
  43. $_GET['page'] = $i;
  44. $this->pageIndex[$index] = http_build_query($_GET);
  45. }
  46. }
  47. /**
  48. * 返回分页信息数据
  49. * @return [type] [description]
  50. */
  51. public function show(){
  52. return $this->pageIndex;
  53. }
  54. }
  55. ?>

缩略图类

  1. <?php
  2. /**
  3. * 缩略图类
  4. * @author webbc
  5. */
  6. class Thumb{
  7. private $thumbWidth;//缩略图的宽
  8. private $thumbHeight;//缩略图的高
  9. private $thumbPath;//缩略图保存的路径
  10. private $sourcePath;//原图的路径
  11. private $sourceWidth;//原图的宽度
  12. private $sourceHeight;//原图的高度
  13. private $sourceType;//原图的图片类型
  14. /**
  15. * 构造函数
  16. * @param str $sourcePath 原图的绝对路径
  17. * @param integer $thumbWidth 缩略图的宽
  18. * @param integer $thumbHeight 缩略图的高
  19. */
  20. public function __construct($sourcePath,$thumbWidth=200,$thumbHeight=200){
  21. //获取原图的绝对路径
  22. $this->sourcePath = $sourcePath;
  23. //获取缩略图的大小
  24. $this->thumbWidth = $thumbWidth;
  25. $this->thumbHeight = $thumbHeight;
  26. $this->thumbPath = $this->getThumbPath();
  27. //计算大图的大小
  28. list($this->sourceWidth,$this->sourceHeight,$this->sourceType) = getimagesize($this->sourcePath);
  29. }
  30. /**
  31. * 确定缩略图保存的路径
  32. * @return [type] [description]
  33. */
  34. private function getThumbPath(){
  35. $ext = $this->getExt();
  36. $filename = basename($this->sourcePath,'.'.$ext).'_thumb'.'.'.$ext;
  37. return $thumbPath = __DIR__.'/'.$filename;
  38. }
  39. /**
  40. * 获取原图的扩展名
  41. * @return str 扩展名
  42. */
  43. private function getExt(){
  44. return pathinfo($this->sourcePath,PATHINFO_EXTENSION);
  45. }
  46. /**
  47. * 检测原图的扩展名是否合法,并返回相应类型
  48. * @return bool/str 原图的类型
  49. */
  50. public function getType(){
  51. $typeArr = array(
  52. 1 => 'gif',
  53. 2 => 'jpeg',
  54. 3 => 'png',
  55. 15 => 'wbmp'
  56. );
  57. if(!in_array($this->sourceType, array_keys($typeArr))){
  58. return false;
  59. }
  60. return $typeArr[$this->sourceType];
  61. }
  62. /**
  63. * 按照缩略图大小,计算大图的缩放比例
  64. * @return float 缩放比例
  65. */
  66. public function calculateRate(){
  67. return min($this->thumbWidth / $this->sourceWidth,$this->thumbHeight / $this->sourceHeight);
  68. }
  69. /**
  70. * 计算大图按照缩放比例后,最终的图像大小
  71. * @param float $rate 缩放比例
  72. * @return arr 缩放后的图片大小
  73. */
  74. public function getImageSizeByRate($rate){
  75. $width = $this->sourceWidth * $rate;
  76. $height = $this->sourceHeight * $rate;
  77. return array('w'=>$width,'h'=>$height);
  78. }
  79. /**
  80. * 保存成文件
  81. * @return [type] [description]
  82. */
  83. public function saveFile($image){
  84. $method = "image".$this->getType();
  85. $method($image,$this->thumbPath);
  86. }
  87. /**
  88. * 进行绘画操作
  89. * @return [type] [description]
  90. */
  91. public function draw(){
  92. if(!($type = $this->getType())){
  93. echo "文件类型不支持";
  94. return ;
  95. }
  96. //创建大图和小图的画布
  97. $method = "imagecreatefrom".$type;
  98. $bigCanvas = $method($this->sourcePath);
  99. $smallCanvas = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight);
  100. //创建白色画笔,并给小图画布填充背景
  101. $white = imagecolorallocate($smallCanvas, 255, 255, 255);
  102. imagefill($smallCanvas, 0, 0, $white);
  103. //计算大图的缩放比例
  104. $rate = $this->calculateRate();
  105. //计算大图缩放后的大小信息
  106. $info = $this->getImageSizeByRate($rate);
  107. //进行缩放
  108. imagecopyresampled($smallCanvas, $bigCanvas,
  109. ($this->thumbWidth - $info['w']) / 2 , ($this->thumbHeight - $info['h']) / 2,
  110. 0, 0, $info['w'], $info['h'], $this->sourceWidth, $this->sourceHeight);
  111. //保存成文件
  112. $this->saveFile($smallCanvas);
  113. //销毁画布
  114. imagedestroy($bigCanvas);
  115. imagedestroy($smallCanvas);
  116. }
  117. }
  118. ?>

上传类

  1. <meta charset="utf8"/>
  2. <?php
  3. /**
  4. * 文件上传类
  5. * @author webbc
  6. */
  7. class Upload{
  8. private $allowExt = array('gif','jpg','jpeg','bmp','png','swf');//限制文件上传的后缀名
  9. private $maxSize = 1;//限制最大文件上传1M
  10. /**
  11. * 获取文件的信息
  12. * @param str $flag 上传文件的标识
  13. * @return arr 上传文件的信息数组
  14. */
  15. public function getInfo($flag){
  16. return $_FILES[$flag];
  17. }
  18. /**
  19. * 获取文件的扩展名
  20. * @param str $filename 文件名
  21. * @return str 文件扩展名
  22. */
  23. public function getExt($filename){
  24. return pathinfo($filename,PATHINFO_EXTENSION);
  25. }
  26. /**
  27. * 检测文件扩展名是否合法
  28. * @param str $filename 文件名
  29. * @return bool 文件扩展名是否合法
  30. */
  31. private function checkExt($filename){
  32. $ext = $this->getExt($filename);
  33. return in_array($ext,$this->allowExt);
  34. }
  35. /**
  36. * 检测文件大小是否超过限制
  37. * @param int size 文件大小
  38. * @return bool 文件大小是否超过限制
  39. */
  40. public function checkSize($size){
  41. return $size < $this->maxSize * 1024 * 1024;
  42. }
  43. /**
  44. * 随机的文件名
  45. * @param int $len 随机文件名的长度
  46. * @return str 随机字符串
  47. */
  48. public function randName($len=6){
  49. return substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ234565789'),0,$len);
  50. }
  51. /**
  52. * 创建文件上传到的路径
  53. * @return str 文件上传的路径
  54. */
  55. public function createDir(){
  56. $dir = './upload/'.date('Y/m/d',time());
  57. if(is_dir($dir) || mkdir($dir,0777,true)){
  58. return $dir;
  59. }
  60. }
  61. /**
  62. * 文件上传
  63. * @param str $flag 文件上传标识
  64. * @return arr 文件上传信息
  65. */
  66. public function uploadFile($flag){
  67. if($_FILES[$flag]['name'] === '' || $_FILES[$flag]['error'] !== 0){
  68. echo "没有上传文件";
  69. return;
  70. }
  71. $info = $this->getInfo($flag);
  72. if(!$this->checkExt($info['name'])){
  73. echo "不支持的文件类型";
  74. return;
  75. }
  76. if(!$this->checkSize($info['size'])){
  77. echo "文件大小超过限制";
  78. return;
  79. }
  80. $filename = $this->randName().'.'.$this->getExt($info['name']);
  81. $dir = $this->createDir();
  82. if(!move_uploaded_file($info['tmp_name'], $dir.'/'.$filename)){
  83. echo "文件上传失败";
  84. }else{
  85. return array('filename'=>$filename,'dir'=>$dir);
  86. }
  87. }
  88. }
  89. ?>

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP网络编程技巧总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

人气教程排行