博客列表 > PHP7.0 以上 面向对象封装的数据库(基)类

PHP7.0 以上 面向对象封装的数据库(基)类

littler_two的博客
littler_two的博客原创
2017年08月16日 14:57:59729浏览

<?php
$config = include 'config.php';
$model = new Model($config);
class Model
{
//链接
protected $link;
//主机名
protected $host;
//用户名
protected $user;
//密码
protected $pwd;
//字符集
protected $charset;
//库名
protected $dbName;
//表名
protected $table = 'user';
//字段
protected $fields;
//表前缀
protected $prefix;
//Sql
protected $sql;
//选项
protected $options;

//初始化成员属性
public function __construct($config)
{
$this->host = $config['DB_HOST'];
$this->user = $config['DB_USER'];
$this->pwd = $config['DB_PWD'];
$this->charset = $config['DB_CHARSET'];
$this->dbName = $config['DB_NAME'];
$this->prefix = $config['DB_PREFIX'];

//数据类链接

$this->link = $this->connect();
//获取表名
$this->table = $this->getTable();
//获取字段
$this->fields = $this->getFields();
}
//根据特定字段查询
protected function getBy($field,$val)
{
$sql = "select * from $this->table where $field = '$val'";


$result = $this->query($sql);
return $result;
}

//求和
public function sum($field = null)
{
if (empty($field)) {
$field = $this->fields['_pk'];
} else {
$field = $field;
}

$sql = "select sum($field) as m from $this->table";

$result = $this->query($sql);
return $result[0]['m'];
}
//查询总数
public function count($field = null)
{
if (empty($field)) {
$field = $this->fields['_pk'];
} else {
$field = $field;
}

$sql = "select count($field) as m from $this->table";

$result = $this->query($sql);
return $result[0]['m'];
}
//查询最小值
public function min($field = null)
{
if (empty($field)) {
$field = $this->fields['_pk'];
} else {
$field = $field;
}

$sql = "select min($field) as m from $this->table";

$result = $this->query($sql);
return $result[0]['m'];
}
//查询最大值
public function max($field = null)
{
if (empty($field)) {
$field = $this->fields['_pk'];
} else {
$field = $field;
}

$sql = "select max($field) as m from $this->table";

$result = $this->query($sql);
return $result[0]['m'];
}
//删除方法
public function delete()
{
//delete from table where
$sql = 'DELETE FROM %TABLE% %WHERE%';
$sql = str_replace(
array('%TABLE%','%WHERE%'),
array(
$this->parseTable(),
$this->parseWhere()
),
$sql
);
return $this->exec($sql);
}

//update 方法
public function update($data)
{
if (!is_array($data)) {
return false;
}

// update table set WHERE ;

$sql = 'UPDATE  %TABLE% %SET% %WHERE%';
$sql = str_replace(
array('%TABLE%','%SET%','%WHERE%'),
array(
$this->parseTable(),
$this->parseSet($data),
$this->parseWhere()
),
$sql
);
return $this->exec($sql);
}
//修改方法里的set
protected function parseSet($data)
{
//var_dump($data);

$str = '';
foreach ($data as $key => $val) {
$str .= $key .'='. "'$val',";
}
return 'SET '.rtrim($str,',');
}
//添加方法
public function add($data)
{
if (!is_array($data)) {
return false;
}
//var_dump($data);
// insert into table fields values ();

$sql = 'INSERT INTO %TABLE% (%FIELDS%) VALUES(%VALUES%)';
$sql = str_replace(
array('%TABLE%','%FIELDS%','%VALUES%'),
array(
$this->parseTable(),
$this->parseAddFields(array_keys($data)),
$this->parseAddVal(array_values($data))
),
$sql
);
return $this->exec($sql);

}

//执行
protected function exec($sql)
{
$result = mysqli_query($this->link,$sql);

if ($result) {
return mysqli_insert_id($this->link);
} else {
return false;
}
}
//处理添加方法里的值
protected function parseAddVal($data)
{
//'小胖凯','22222'
$str = '';
foreach ($data as $val) {
$str .= '\''.$val.'\',';
}
$str = rtrim($str,',');
return $str;
}
//处理添加方法里的字段
protected function parseAddFields($data)
{
return join(',',$data);
}
//查询方法
public function select()
{
//var_dump($this->options);
//$sql = select %字段% from %table% %where% %group% %having% %order% %limit% 
$sql = 'SELECT %FIELDS% FROM %TABLE% %WHERE% %GROUP% %HAVING% %ORDER% %LIMIT%';
$sql = str_replace(
array('%FIELDS%','%TABLE%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'),
array(
$this->parseFields(isset($this->options['fields']) ? $this->options['fields'] : null),
$this->parseTable(),
$this->parseWhere(),
$this->parseGroup(),
$this->parseHaving(),
$this->parseOrder(),
$this->parseLimit()
),
$sql
);
$data = $this->query($sql);
return $data;
}
//处理查询方法里面的limit
protected function parseLimit()
{
if (empty($this->options['limit'])) {
$limit = '';
} else {
//var_dump($this->options['limit']);
if  (is_string($this->options['limit'][0])) {
$limit = 'LIMIT '.$this->options['limit'][0];

} elseif (is_array($this->options['limit'][0])) {
$limit = 'LIMIT '.join(',',$this->options['limit'][0]);
}
}
return $limit;
}
//处理查询方法里面的order
protected function parseOrder()
{
if (empty($this->options['order'])) {
$order = '';
} else {
$order = 'ORDER BY '.$this->options['order'][0];
}
return $order;
}
//处理查询方法里面的having
protected function parseHaving()
{
//var_dump($this->options);
if (empty($this->options['having'])) {
$having = '';
} else {
$having = 'HAVING '.$this->options['having'][0];
}
return $having;
}
//处理查询方法里面的group
protected function parseGroup()
{
//var_dump($this->options);
if (empty($this->options['group'])) {
$group = '';
} else {
$group = 'GROUP BY '.$this->options['group'][0];
}
return $group;
}
//处理查询方法里面的where
protected function parseWhere()
{
//var_dump($this->options);
if (empty($this->options['where'])) {
$where = '';
} else {
$where = 'WHERE '.$this->options['where'][0];
}
return $where;
}
//处理查询方法里面的table

protected function parseTable()
{
//var_dump($this->options);
if (isset($this->options['table'])) {
$table = $this->prefix . $this->options['table'][0];
} else {
$table = $this->table;
}
return $table;
}
//处理查询方法里面的字段
protected function parseFields($options = null)
{
//var_dump($options);
if (empty($options)) {
return '*';
} else {
if (is_string($options[0])) {
$f = explode(',',$options[0]);
$newArr = array_intersect($f,$this->fields);
$fields = join(',',$newArr);
}

if (is_array($options[0])) {
$fields = join(',',array_intersect($options[0],$this->fields));
}
return $fields;
}

}

//通过call 方法来实现连贯操作
public function __call($func,$args)
{
if (in_array($func,array('fields','table','where','group','having','order','limit'))) {
$this->options[$func] = $args;
return $this;
} else if(strtolower(substr($func,0,5)) == 'getby') {
$field = strtolower(substr($func,5));
return $this->getBy($field,$args[0]);
//var_dump($args[0]);
} else {
exit('不存在的方法');
}
}
//获取字段
protected function getFields()
{
$cacheFile = 'cache/'.$this->table.'.php';
if (file_exists($cacheFile)) {
return include $cacheFile;
} else {
$sql = 'DESC '.$this->table;
$data = $this->query($sql);
$fields = [];
foreach ($data as $key => $val) {
$fields[] = $val['Field'];
if ($val['Key']== 'PRI') {
$fields['_pk'] = $val['Field'];
}
}
//echo $sql;
$string = "<?php \n return ".var_export($fields,true).';?>';
file_put_contents('cache/'.$this->table.'.php',$string);
return $fields;
}
}

//写出来query方法
protected function query($sql)
{
$result = mysqli_query($this->link,$sql);

$data = [];
if ($result) {
while ($rows = mysqli_fetch_assoc($result)) {
$data[] = $rows;
}
} else {
return false;
}

return $data;
}
//获取表名字的方法

protected function getTable()
{
$table = '';

if (isset($this->table)) {
$table = $this->prefix . $this->table;
} else {
$table = $this->prefix .strtolower(substr(get_class($this),0,-5));
}

return $table;
}


//数据类链接方法
protected function connect()
{
$conn = mysqli_connect($this->host,$this->user,$this->pwd);

if (!$conn) {
exit('数据裤链接失败');
}
mysqli_set_charset($conn,$this->charset);
mysqli_select_db($conn,$this->dbName);
return $conn;
}

protected function close()
{
mysqli_close($this->link);
}

//关闭数据库
public function __destruct()
{
$this->close();
}

}  //类结束

注:

1.引入config文件

<?PHP
/**
 * 全局的配置文件
 */


return [
//数据库的全局文件
'DB_HOST' => 'localhost',
'DB_USER' => 'root',
'DB_PWD' => '',
'DB_CHARSET' => 'utf8',
'DB_NAME' => 'blog',
'DB_PREFIX' => 'b_',
'DB_CACHE' => 'cache/database',

];


2.该类只是基类  需要具体需要使用它的类来继承它


3.继承之后可以用该类中的所有非private方法


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议