版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/qq_43187460/article/details/88369365
PHP 后台报表设计思路以及常用功能之——时间搜索代码块简单优化思路
相信PHP入门的话,TP框架是大家也接触比较多的一个框架了,今天讲的例子也是用TP框架为例,其实讲代码块优化思路的话,和用什么框架都没关系的,思路大致相同,最终也是殊途同归而已。
直接进入主题吧,是关于后台的一个 关于时间的搜索一个小代码块的,但是复用需求高,几乎整个后台90%需要用到
,先看一下我翻了一些之前别人写的一部代码贴出来看看,以TP框架的写法为例子:
$datemin = I('get.datemin'); //这是接收的参数 底位时间
$datemax = I('get.datemax'); //这是接收的参数 高位时间
// 下面的代码块,看起来好像还可以接受,但其实一但一个文件几乎大部分是这种代码的时候,你就会觉得头大了,这种写法极其不好。
看上去脑阔疼。而且无法复用,已经写死了。试想一下每遇到一个搜索功能,都写这么段代码,可怕。
if ($datemin && $datemax) { //这是判断
$_where = " and `addtime` >='{$datemin}' and `addtime`<='$datemax'";
$order_where = " and `date_purchased` >='{$datemin}' and `date_purchased`<='$datemax'";
} elseif ($datemin) {
$_where = " and `addtime` >='{$datemin}'";
$order_where = " and `date_purchased` >='{$datemin}'";
} elseif ($datemax) {
$_where = " and `addtime` <= '$datemax'";
$order_where = " and `date_purchased` <= '$datemax'";
}
以下是初步优化过的代码块
if(!empty($_GET['datemin'])){ //接收参数
$datetime['datemin'] = str_replace('+',' ',$_GET['datemin']);
}
if(!empty($_GET['datemax'])){
$datetime['datemax'] = str_replace('+',' ',$_GET['datemax']);
}
$whereTime = dateQuery($datetime,['us.addtime']);//如果有时间条件,调用这个函数获取查询语句。
以上2段代码,我想哪一段更简洁,已经显而易见了,其实要实现不难,只要写一个公共函数去帮我们自动去处理,返回我们想要的结果,就行了,dateQuery() 的代码如下:
//时间搜索条件自动判断函数
/**
* @param $datetime //一维数组类型的时间段条件,时间戳格式 数组键名 :datemin datemax 规范写法
* @param $query //要判断的表,时间字段名 一维数组。
* @return mixed //返回可以直接当作TP查询语句 where(mixed);
*/
function dateQuery($datetime,array $query)
{
if($datetime){
//时间范围的查询条件
if(count($datetime) == 1){
//如果只有一个时间段
foreach ($datetime as $key => $value) {
if (!empty($datetime[$key])) {
if($key == 'datemin'){
$E = 'egt';
}elseif($key == 'datemax'){
$E = 'elt';
}
foreach ($query as $vo){
$where[$vo] = array($E, $value);
}
}
}
}else{
$datemin = $datetime['datemin'];
$datemax = $datetime['datemax'];
foreach ($query as $vo){
$where[$vo] = array(array('EGT',$datemin),array('ELT',$datemax));
}
}
}
return $where;
}
其实以上就是个很简单的入门思路,其实以上代码还有可以继续优化的地方,但是暂时先写到这。
我们可以让函数,替我们自动去完成一些代码的编写,一些自动操作等,避免了杂乱又重复的代码垃圾,让代码更简洁,提高可读性,可维护性,易更改性,等。