PHP常用封装类
1、mysql.class.php
<?php
// namespace Package; /**
* MySQL 类
* @author cxm <tsai.er6@gmail.com>
*
*/
class MySQL
{ private static $link = null; //数据库连接 /**
* 私有的构造方法
*/
private function __construct() {} /**
* 连接数据库
* @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']);
}
return self::$link;
} /**
* 执行一条sql语句
* @param str $sql 查询语句
* @return obj 结果集对象
*/
public static function query($sql)
{
return self::conn()->query($sql);
} /**
* 获取多行数据
* @para str $sql 查询语句
* @return arr 多行数据
*/
public static function getAll($sql)
{
$data = array();
$res = self::query($sql);
while (($row = $res->fetch_assoc()) != FALSE)
{
$data[] = $row;
}
return $data;
} /**
* 获取一行数据
* @param str $row 查询语句
* @return arr 单行数据
*/
public static function getRow($sql)
{
$res = self::query($sql);
return $res->fetch_assoc();
} /**
* 获取单个结果
* @param str $sql 查询语句
* @return str 单个结果
*/
public static function getOne($sql)
{
$res = self::query($sql);
$data = $res->fetch_row();
return $data[0];
} /**
* 插入/更新数据
* @param str $table 表明
* @param arr $data 插入/更新的数据
* @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;
} /**
* 获取最近一次操作影响的行数
* @return int 影响的行数
*/
public static function getAffectedRows()
{
return self::conn()->affected_rows();
} /**
* 关闭数据库连接
* @return bool 是否关闭
*/
public static function close()
{
return self::conn()->close();
} } ?>
2.page.class.php
<?php
// namespace Package; /**
* 分页类
* @author cxm <tsai.er6@gmail.com>
*
*/
class Page
{
private $num; //总的文章数
private $cnt; //每页显示的文章数
private $curr; //当前的页码数
private $p = 'page'; //分页参数名
private $pageCnt = 5; //分栏总共显示的页数
private $firstRow; //每页的第一行数据
private $pageIndex = array(); //分页信息 /**
* 构造函数
* @param int $num 总的文章数
* @param int $cnt 每页显示的文章数
*/
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); //总的页数
$left = max(1, $this->curr - floor($this->pageCnt/2)); //计算最左边页码
$right = min($left + $this->pageCnt - 1, $page); //计算最右边页码
$left = max(1, $right - ($this->pageCnt - 1)); //当前页码往右靠,需要重新计算左边页面的值
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);
}
} /**
* 返回分页信息数据
* @return [type] [description]
*/
public function show()
{
return $this->pageIndex;
}
} ?>
3.thumb.class.php
<?php /**
* 缩略图类
* @author cxm <tsai.er6@gmail.com>
*
*/ class Thumb
{
private $thumbWidth; //缩略图的宽
private $thumbHeight; //缩略图的高
private $thumbPath; //缩略图保存的路径 private $sourcePath; //原图的路径
private $sourceWidth; //原图的宽度
private $sourceHeight; //原图的高度
private $sourceType; //原图的图片类型 /**
* 构造函数
* @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();
// 计算大图的大小
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;
} /**
* 获取原图的扩展名
* @return str 扩展名
*/
private function getExt()
{
return pathinfo($this->sourcePath, PATHINFO_EXTENSION);
} /**
* 检测原图的扩展名是否合法,并返回相应类型
* @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];
} /**
* 按照缩略图大小,计算大图的缩放比例
* @return float 缩放比例
*/
public function calculateRate()
{
return min($this->thumbWidth / $this->sourceWidth, $this->thumbHeight / $this->sourceHeight);
} /**
* 计算大图按照缩放比例后,最终的图像大小
* @param float $rate 缩放比例
* @return arr 缩放后的图片大小
*/
public function getImageSizeRate($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);
} /**
* 进行绘画操作
* @return [type] [description]
*/
public function draw()
{
if (!($type = $this->getType()))
{
echo "文件类型不支持";
return;
}
// 创建大图和小图的画布
$method = "imagecreatefrom".$type;
$bigCanvas = $method($this->sourcePath);
$smallCanvas = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight);
// 创建白色画笔,并给小图画布填充背景
$white = imagecolorallocate($smallCanvas, 255, 255, 255);
imagefill($smallCanvas, 0, 0, $white);
// 计算大图的缩放比例
$rate = $this->calculateRate();
// 计算大图缩放后的大小信息
$info = $this->getImageSizeRate($rate);
// 进行缩放
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);
}
} ?>
4.upload.class.php
<meta charset="utf8"/>
<?php /**
* 文件上传类
* @author cxm <tsai.er6@gmail.com>
*/ class Upload
{
private $allowExt = array('gif','jpg','jpeg','bmp','png','swf'); //显示文件上传的后缀名
private $maxSize = 1; //限制最大文件上传1M /**
* 获取文件的信息
* @param str $flag 上传文件的标识
* @return arr 上传文件的信息数组
*/
public function getInfo($flag)
{
return $_FILES[$flag];
} /**
* 获取文件的扩展名
* @param str $filename 文件名
* @return str 文件扩展名
*/
public function getExt($filename)
{
return pathinfo($filename, PATHINFO_EXTENSION);
} /**
* 检测文件扩展名是否合法
* @param str $filename 文件名
* @return bool 文件扩展名是否合法
*/
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;
} /**
* 随机的文件名
* @param int $len 随机文件名的长度
* @return str 随机字符串
*/
public function randName($len = 6)
{
return substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMKOPQRSTUVWXYZ0123456789'),0,$len);
} /**
* 创建文件上传到的路径
* @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 文件上传标识
* @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);
}
}
} ?>
PHP常用封装类的更多相关文章
- PHP AES加密封装类
简介 PHP AES 加密解密常用封装类 使用方式 $key = 123; $aes = new Aes($key); $data = ['a' => 1]; $aes->decrypt( ...
- MSCL超级工具类(C#),开发人员必备,开发利器
MSCL超强工具类库 是基于C#开发的超强工具类集合,涵盖了日常B/S或C/S开发的诸多方面,包含上百个常用封装类(数据库操作类全面支持Mysql.Access.Oracle.Sqlserver.Sq ...
- Java 常用对象-基本类型的封装类
2017-11-04 20:39:26 基本类型封装类:基本类型的封装类的好处是可以在对象中定义更多的功能方法操作该数据. 常用操作之一:用于基本数据类型与字符串的转换. 基本类型和包装类的对应: b ...
- Java调用外部程序常用算法和封装类
一个项目不可能只使用一种编程语言来开发,也不可能由一个人开发,所以,Java程序员要学会和使用其他编程语言的程序员合作.那么,让我来发布一个工具类--Java外接程序扩展包,并将相应算法发布.Java ...
- Android常用的工具类SharedPreferences封装类SPUtils
package com.zhy.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect. ...
- Android 常用数据操作封装类案例
1.DbHelper类 继承自SQLiteOpenHelper类,实现对数据库的基本操作 package com.example.utils; import android.content.Conte ...
- Android快速开发系列 10个常用工具类
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...
- android常用对话框封装
在android开发中,经常会用到对话框跟用户进行交互,方便用户可操作性:接下来就对常用对话框进行简单封装,避免在项目中出现冗余代码,加重后期项目的维护量:代码如有问题欢迎大家拍砖指正一起进步. 先贴 ...
- android 常用类
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...
随机推荐
- HDU5319
题意:给一个矩形染色,顺笔表示红色,逆笔表示蓝色(既一捺和一丿),交叉表示绿色,然后给你一个图,问你用多少笔能画出这个图来. 思路:对这个图直接模拟即可,如果点i,j坐标为红色,那么判断上一个路径点是 ...
- 关于Linux下面msyql安装后并未设置初始密码,但是登录报错“Access denied for user 'root'@'localhost' (using password: NO)”的解决方案
如上图:首先我安装mysql的时候并没有设置密码,但是就是登不进去,百度了一下,解决方案如下: 解决方案地址:http://zhidao.baidu.com/link?url=7QvuOKtfRdMT ...
- iOS开发: 向右滑动手势功能实现
在navigationController中实现向右滑动 返回功能 系统提供的backbarbuttonitem,不用添加任何代码即可实现向右滑动后退功能,但是往往要对按钮修改样式等时,就需要自定义l ...
- POJ 1240 Pre-Post-erous! 解题报告
题意: 给出一个m叉树的前,后序遍历求这样的树有多少种. Solution: 我们知道前序遍历的第一个点一定是根节点,后序遍历的最后一个点一定是根节点. 由此,我们只一要确定对于每一个节点,它有多少个 ...
- select、pselect、poll和epoll的区别
select.pselect.poll和epoll函数是unix中具有I/O复用的函数.什么是I/O复用?为什么要有I/O复用?以及在什么场合下使用I/O复用?既然都具有I/O复用的功能,那这几个函数 ...
- CRM窗体中只读的控件不会引发Update事件
在CRM的窗体设计时,如果把某一个控件设为只读了,仅管你在后台用代码修改了值,这个值也不会起任何作用,更不会提交到后台,触发Update事件!
- javascript权威指南学习笔记2
Javascript语言核心(2~12章) 第三章:类型.值.变量 1.数字: overflow(Infinity, -Infinity).underflow(+0,-0) 非数字值:它和任何值都不相 ...
- 更快的使用你的键盘:AUTOHOTKEY
本文适合于:每天用电脑工作学习的朋友.游戏发烧手指又不灵敏的朋友.希望提高自己使用电脑效率的朋友. 本文将将告诉你AutoHotkey能做什么,并会一步一步地教会你轻易地使用它,但不会教你更多Auto ...
- GFStableList Adapter
STL中,list的优点是插入.删除性能极佳(时间复杂度只需O(1)即可),而且非常重要的在删除节点后,其迭代器不失效,但list查找却不擅长.map由于其实现的数据结构为rb-tree,因此,其插入 ...
- python -i filename
今天学习的时候看见python -i filaname 这个命令,书上说使用这个命令可以去执行filename文件中的代码.但是今天在使用的时候却一直报错,经过多次测试才把问题解决. 原来这个命令是不 ...