首页 实用干货🍩

封装常用的工具类,不写重复代码,能极大的提高开发效率。

工具类函数

Geom转成字符串

如果项目中有大量的计算经纬度需求,强烈建议使用PgSqlgeometry类型

public static function formatGeomToStr($geomJson)
{
    if (empty($geomJson)) {
        return null;
    }
    $geomStr = '';
    $data = json_decode($geomJson, true);
    if ($data['lng'] !== '' && $data['lat'] !== '') {
        $geomStr = "POINT({$data['lng']} {$data['lat']})";
    }

    return $geomStr;
}

计算两个坐标之间的距离

基于经纬度进行计算

public static function calcDistance($loc1, $loc2)
{
    if (empty($loc1) || empty($loc2) || count($loc2) != 2 || count($loc1) != 2) {
        return -1;
    }

    $radLat1 = deg2rad(floatval($loc1['lat']));
    $radLat2 = deg2rad(floatval($loc2['lat']));
    $radLng1 = deg2rad(floatval($loc1['lng']));
    $radLng2 = deg2rad(floatval($loc2['lng']));
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
    return round($s, 3);
}

批量更新数据拼接sql

这是我司大佬整理的,我就拿来主义贡献给大家了

//批量写入
public static function batchUpdate($multipleData, $tableName)
{
    $firstRow = current($multipleData);

    $updateColumn = array_keys($firstRow);
    $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
    unset($updateColumn[0]);
    // 拼接sql语句
    $updateSql = "UPDATE " . $tableName . " SET ";
    $sets = [];
    $bindings = [];
    foreach ($updateColumn as $uColumn) {
        $setSql = '"' . $uColumn . '" = CASE ';
        foreach ($multipleData as $data) {
            $setSql .= 'WHEN "' . $referenceColumn . '" = ? THEN ? ';
            $bindings[] = $data[$referenceColumn];
            $bindings[] = $data[$uColumn];
        }
        $setSql .= 'ELSE "' . $uColumn . '" END ';
        $sets[] = $setSql;
    }
    $updateSql .= implode(', ', $sets);
    $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
    $bindings = array_merge($bindings, $whereIn);
    $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
    $updateSql = rtrim($updateSql, ", ") . ' WHERE "' . $referenceColumn . '" IN (' . $whereIn . ")";
    return DB::connection('myProject')->update($updateSql, $bindings);
}

格式化时间

最常用的工具了吧,几乎每个项目都会用到

public static function formatTimestampForClient($timestamp)
{
    $formatString = '';
    $now = time();
    //一个小时内
    $diffTime = $now - $timestamp;
    if ($diffTime < 60) {
        $formatString = '刚刚';
    } else if ($diffTime < 3600) {
        $formatString = intval($diffTime / 60) . "分钟前";
    } else if ($diffTime < 12 * 3600) {
        $formatString = intval($diffTime / 3600) . "小时前";
    } else if ($diffTime < 24 * 3600) {
        $formatString = "1天内";
    } else if ($diffTime < 3 * 24 * 3600) {
        $formatString = "3天内";
    }

    return $formatString;
}

获得随机字符串

第二个参数表示是否允许包括特殊字符

public static function getRandomStr($len, $special = true)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );

    if ($special) {
        $chars = array_merge($chars, array(
            "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
            "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
            "}", "<", ">", "~", "+", "=", ",", "."
        ));
    }

    $charsLen = count($chars) - 1;
    shuffle($chars);                            //打乱数组顺序
    $str = '';
    for ($i = 0; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
    }
    return $str;
}

根据生日计算星座

星座控看这里

public static function getZodiacSign($birth)
{
    $month = date('m', $birth);
    $day = date('d', $birth);
    $signs = [
        ["20" => "水瓶座"],
        ["19" => "双鱼座"],
        ["21" => "白羊座"],
        ["20" => "金牛座"],
        ["21" => "双子座"],
        ["22" => "巨蟹座"],
        ["23" => "狮子座"],
        ["23" => "处女座"],
        ["23" => "天秤座"],
        ["24" => "天蝎座"],
        ["22" => "射手座"],
        ["22" => "摩羯座"]
    ];
    $signStart = array_key_first($signs[$month - 1]);
    $signName = $signs[$month - 1][$signStart];
    if ($day < $signStart) {
        $sign = array_values($signs[($month - 2 < 0) ? $month = 11 : $month -= 2]);
        $signName = array_shift($sign);
    }
    return $signName;
}

校验手机号的正确性

最常用的工具类之二

注意:各运营商投放的号段会有更新,可以不定期的查询一下,更新这个工具类

public static function checkPhoneNumber($phone_number)
{
    //中国联通号码:130、131、132、145(无线上网卡)、155、156、185(iPhone5上市后开放)、186、176(4G号段)、175(2015年9月10日正式启用,暂只对北京、上海和广东投放办理),166,146
    //中国移动号码:134、135、136、137、138、139、147(无线上网卡)、148、150、151、152、157、158、159、178、182、183、184、187、188、198
    //中国电信号码:133、153、180、181、189、177、173、149、199
    $g = "/^1[34578]\d{9}$/";
    $g2 = "/^19[89]\d{8}$/";
    $g3 = "/^166\d{8}$/";
    if (preg_match($g, $phone_number)) {
        return true;
    } else if (preg_match($g2, $phone_number)) {
        return true;
    } else if (preg_match($g3, $phone_number)) {
        return true;
    }
    return false;
}

生成唯一标识:32位自定义字符串

Uuid 是一个非常好用的工具

public static function createUniqueId()
{
    $uuid5 = Uuid::uuid4();
    $uid = str_replace('-', '', $uuid5->toString());

    return strtoupper($uid);
}

获得毫秒

public static function getMicroSecond()
{
    return intval(microtime(true) * 1000);
}

生成订单号

电商项目必备

public static function createOrderId()
{
    $microSecond = Utility::getMicroSecond();
    return date("YmdHis", $microSecond / 1000) . sprintf("%03d", $microSecond % 1000) . rand(100000, 999999);
}

判断是否是json

public static function isJson($value)
{
    $data = json_decode($value, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return false;
    } else if (!is_array($data)) {
        return false;
    }

    return true;
}

获得ip

public static function getIp()
{
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    return $realip;
}

获得N天前、N天后时间戳

传入N值是一个比较好的思路,我之前搞了几个3天前、7天前、30天前这类的工具。

都不如传入N值来的科学。

//获取N天的0点时间戳
public static function getNDayTimestamp($n = 1)
{
    return strtotime(date('Y-m-d', strtotime('+' . $n . ' day')));
}

//获取N天前0点时间戳
public static function getBeforeNDayTimestamp($n = 1)
{
    return strtotime(date('Y-m-d', strtotime('-' . $n . ' day')));
}

手机号掩码

public static function maskPhone($phone)
{
    $strLen = strlen($phone);
    if ($strLen < 4) {
        return '';
    } else {
        return substr_replace($phone, "****", 3, 4);
    }
}

判断时间戳是否是今天

public static function isToday($timestamp = 0)
{
    $res = false;
    if (date('Ymd', $timestamp) == date('Ymd')) {
        $res = true;
    }
    return $res;
}

大家还有哪些需要使用工具类的场景,欢迎在评论区留言,我来实现补充。