Laravel 提供了很多 辅助函数,有时候我们也需要创建自己的辅助函数。

我们把所有的『自定义辅助函数』存放于 app/Helpers/functions.php 文件中,这里需要新建一个空文件:

在我们新增functions.php文件之后,还需要在项目根目录下 composer.json 文件中的 autoload 选项里 files 字段加入该文件:

composer.json

{..."autoload": {"psr-4": {"App\\": "app/"},"classmap": ["database/seeds","database/factories"],"files":["app/Helpers/functions.php"]}...
}

修改保存后运行以下命令进行重新加载文件即可:

composer dump-autoload

常用帮助函数

<?php
/*** 通用辅助函数*/use Hashids\Hashids;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;/**
* 格式化特殊字符串等
* @param  $strParam         需要格式化的参数
* @return string            格式化结果*/function replaceSpecialChar($strParam)
{$regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";return preg_replace($regex, "", $strParam);}/**
* 格式化字节大小
* @param  number $size      字节数
* @param  string $delimiter 数字和单位分隔符
* @return string            格式化后的带单位的大小*/
function get_byte($size, $delimiter = '') {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
return round($size, 2) . $delimiter . $units[$i];
}/*** 产生随机字符串** @param    int        $length  输出长度* @param    string     $chars   可选的 ,默认为 0123456789* @return   string     字符串*/
function get_random($length, $chars = '0123456789') {$hash = '';$max = strlen($chars) - 1;for($i = 0; $i < $length; $i++) {$hash .= $chars[mt_rand(0, $max)];}return $hash;
}/***  作用:将xml转为array*/
function xmlToArray($xml) {//将XML转为array$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);return $array_data;
}/*** 反字符 去标签 自动加点 去换行 截取字符串*/
function cutstr ($data, $no, $le = '') {$data = strip_tags(htmlspecialchars_decode($data));$data = str_replace(array("\r\n", "\n\n", "\r\r", "\n", "\r"), '', $data);$datal = strlen($data);$str = msubstr($data, 0, $no);$datae = strlen($str);if ($datal > $datae)$str .= $le;return $str;
}/*** [字符串截取]* @param  [type]  $Str    [字符串]* @param  [type]  $Length [长度]* @param  boolean $more   [模型]* @return [type]          [截取后的字符串]*/
function cut($Str, $Length,$more=true) {//$Str为截取字符串,$Length为需要截取的长度global $s;$i = 0;$l = 0;$ll = strlen($Str);$s = $Str;$f = true;while ($i <= $ll) {if (ord($Str{$i}) < 0x80) {$l++; $i++;} else if (ord($Str{$i}) < 0xe0) {$l++; $i += 2;} else if (ord($Str{$i}) < 0xf0) {$l += 2; $i += 3;} else if (ord($Str{$i}) < 0xf8) {$l += 1; $i += 4;} else if (ord($Str{$i}) < 0xfc) {$l += 1; $i += 5;} else if (ord($Str{$i}) < 0xfe) {$l += 1; $i += 6;}if (($l >= $Length - 1) && $f) {$s = substr($Str, 0, $i);$f = false;}if (($l > $Length) && ($i < $ll) && $more) {$s = $s . '...'; break; //如果进行了截取,字符串末尾加省略符号“...”}}return $s;
}/*** 将一个字符串转换成数组,支持中文* @param string    $string   待转换成数组的字符串* @return string   转换后的数组*/
function strToArray($string) {$strlen = mb_strlen($string);while ($strlen) {$array[] = mb_substr($string, 0, 1, "utf8");$string = mb_substr($string, 1, $strlen, "utf8");$strlen = mb_strlen($string);}return $array;
}/**
* 对查询结果集进行排序
* @access public
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby='asc') {if(is_array($list)){$refer = $resultSet = array();foreach ($list as $i => $data)$refer[$i] = &$data[$field];switch ($sortby) {case 'asc': // 正向排序asort($refer);break;case 'desc':// 逆向排序arsort($refer);break;case 'nat': // 自然排序natcasesort($refer);break;}foreach ( $refer as $key=> $val)$resultSet[] = &$list[$key];return $resultSet;}return false;
}// 格式化api返回值 0=成功 其他=失败
if (!function_exists('formatResponse')) {function formatResponse($code, $msg, &$data = null){if (empty($data)) $data = (object)[];return response()->json(['code' => $code, 'msg' => $msg, 'data' => $data]);}
}// 获取客户端IP
if (!function_exists('getIp')) {function getIp($ip2long = false){$ip = '';if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);$pos = array_search('unknown', $arr);if (false !== $pos) unset($arr[$pos]);$ip = trim($arr[0]);} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {$ip = $_SERVER['HTTP_CLIENT_IP'];} elseif (isset($_SERVER['REMOTE_ADDR'])) {$ip = $_SERVER['REMOTE_ADDR'];}if (!empty($ip) && $ip2long) $ip = bindec(decbin(ip2long($ip)));return $ip;}
}// curl 请求
if (!function_exists('curlRequest')) {function curlRequest($url, $data = [], $headers = [], $timeout = 10, $method = 'GET'){$curl = curl_init();if (!empty($headers)) {curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);}curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);if (!empty($data) && 'GET' == $method) $method = 'POST';switch ($method) {case 'POST':curl_setopt($curl, CURLOPT_POST, 1);curl_setopt($curl, CURLOPT_POSTFIELDS, $data);break;case 'PUT':curl_setopt($curl, CURLOPT_PUT, 1);curl_setopt($curl, CURLOPT_POSTFIELDS, $data);break;case 'DELETE':curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');break;}curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);$output = curl_exec($curl);if (curl_errno($curl)) {echo 'Curl error: ' . curl_error($curl);exit;}curl_close($curl);return $output;}
}// 生成订单号
if (!function_exists('generateOrderNumber')) {function generateOrderNumber($prefix = 'S'){$yCode = getCharacters();$index = intval(date('Y')) - 2019;if (1 == $index && 'S' == $prefix) $index = 2; // 过滤SBreturn $prefix . $yCode[$index] . dechex(date('m')) . date('d') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(100, 999);}
}// 获取大/小写英文字符
if (!function_exists('getCharacters')) {function getCharacters($type = 0){if (0 == $type) {return ['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'];} else {return ['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'];}}
}// 获取远程图片大小
if (!function_exists('getRemoteImageSize')) {function getRemoteImageSize($url, &$base64Data = null){getFileDataByCurl($url, $base64Data);return getimagesize('data://image/jpeg;base64,' . $base64Data);}
}// 获取文件数据流
if (!function_exists('getFileDataByCurl')) {function getFileDataByCurl($url, &$data, $type = 0){$ch = curl_init($url);// 超时设置curl_setopt($ch, CURLOPT_TIMEOUT, 30);// 取前面 1000 个字符 若获取不到数据可适当加大数值//curl_setopt($ch, CURLOPT_RANGE, '0-1000');// 跟踪301跳转curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// 返回结果curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$data = curl_exec($ch);curl_close($ch);if (0 == $type) $data = base64_encode($data);}
}// 根据图片路径获取图片的尺寸(宽度&高度)
if (!function_exists('getImageSizeByPath')) {function getImageSizeByPath($imagePath){$flag = 0;$sizeInfo = ['width' => 0, 'height' => 0];if (!empty($imagePath)) {if (false === strpos($imagePath, '_')) $flag = 1;else {$imagePathArr1 = explode('_', $imagePath);if (false === strpos($imagePathArr1[1], '.')) $flag = 1;else {$imagePathArr2 = explode('.', $imagePathArr1[1]);if (false === strpos($imagePathArr2[0], 'x')) $flag = 1;else {$imagePathArr3 = explode('x', $imagePathArr2[0]);$sizeInfo['width'] = $imagePathArr3[0];$sizeInfo['height'] = $imagePathArr3[1];}}}}if (1 == $flag) {//list($width, $height) = getimagesize($imagePath);$imageSize = getRemoteImageSize($imagePath);$sizeInfo['width'] = $imageSize[0];$sizeInfo['height'] = $imageSize[1];}return $sizeInfo;}
}// 请求频率控制
if (!function_exists('requestRateControl')) {function requestRateControl($key, $seconds = 5){$num = Redis::incr($key);if (1 == $num) {Redis::expire($key, $seconds);return true;}return false;}
}// 版本比较
if (!function_exists('versionCompare')) {function versionCompare($version1, $version2){// $version1 < $version2返回 -1// $version1 = $version2返回 0// $version1 > $version2返回 1return version_compare($version1, $version2);}
}/*** PHP 非递归实现查询该目录下所有文件* @param unknown $dir* @return multitype:|multitype:string*/
function scanfiles($dir) {if (! is_dir ( $dir )) return array ();// 兼容各操作系统$dir = rtrim ( str_replace ( '\\', '/', $dir ), '/' ) . '/';// 栈,默认值为传入的目录$dirs = array ( $dir );// 放置所有文件的容器$rt = array ();do {// 弹栈$dir = array_pop ( $dirs );// 扫描该目录$tmp = scandir ( $dir );foreach ( $tmp as $f ) {// 过滤. ..if ($f == '.' || $f == '..')continue;// 组合当前绝对路径$path = $dir . $f;// 如果是目录,压栈。if (is_dir ( $path )) {array_push ( $dirs, $path . '/' );} else if (is_file ( $path )) { // 如果是文件,放入容器中$rt [] = $path;}}} while ( $dirs ); // 直到栈中没有目录return $rt;
}/*** 将list_to_tree的树还原成列表* @param  array $tree  原来的树* @param  string $child 孩子节点的键* @param  string $order 排序显示的键,一般是主键 升序排列* @param  array  $list  过渡用的中间数组,* @return array        返回排过序的列表数组* @author yangweijie <yangweijiester@gmail.com>*/
function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){if(is_array($tree)) {$refer = array();foreach ($tree as $key => $value) {$reffer = $value;if(isset($reffer[$child])){unset($reffer[$child]);tree_to_list($value[$child], $child, $order, $list);}$list[] = $reffer;}$list = list_sort_by($list, $order, $sortby='asc');}return $list;
}//PHP过滤所有特殊字符的函数
function match_chinese($chars,$encoding='utf8')
{$pattern =($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u':'/[\x80-\xFF]/';preg_match_all($pattern,$chars,$result);$temp =join('',$result[0]);return $temp;
}

laravel Helpers文件 通用帮助函数 以及常用帮助方法相关推荐

  1. 使用TkMybatis逆向生成带中文注释文件,并使用其常用的方法

    首先说明,博主用的是springboot,如使用原生态的mybatis的一些配置文件请自行百度 贴上pom文件 <?xml version="1.0" encoding=&q ...

  2. php文件读写用什么函数,php中常用文件操作读写函数介绍_PHP教程

    本文章介绍了下面几个常用的文件操作函数 file_get_contents 读取整个文件内容 fopen 创建和打开文件 fclose 关闭文件 fgets 读取文件一行内容 file_exists ...

  3. C++编程常用头文件及其包含函数汇总

    C++编程常用头文件及其包含函数汇总 1.#include <iostream> #include<iostream>是标准的C++头文件,任何符合标准的C++开发环境都有这个 ...

  4. php打开文件读写函数,php中常用文件操作读写函数介绍

    本文章介绍了下面几个常用的文件操作函数 file_get_contents 读取整个文件内容 fopen 创建和打开文件 fclose 关闭文件 fgets 读取文件一行内容 file_exists ...

  5. python创建文件对象的函数_Python 文件对象常用内建方法

    学习python教程文件操作时,除了 文件对象读取内容 file.read(size):size为读字节的长度,默认为-1. file.readline(size):逐行读取,如果定义了size参数, ...

  6. 020-python函数和常用模块-文件操作

    Python内置函数open,用来打开在磁盘上的文件,并返回一个文件对象,所有对该文件的后续操作都是通过这个"句柄"来进行的. 一.文件操作的三个步骤: 打开文件: 操作文件: 关 ...

  7. [PB] PB中读写文件通用的两个函数

    PB中读写文件通用的两个函数 1.文件读取 : //函数名:f_readfile //功能:读取文件//参数:// io_file:ref blob 大对象类型,存储读出的文件内容:// is_fil ...

  8. Fatfs文件系所有函数总结

    Fatfs文件系统常用函数:f_mount.f_open.f_close.f_read.f_write.f_lseek.f_truncate.f_sync.f_opendir FatFS是一个为小型嵌 ...

  9. python数组去重函数_Python常用功能函数系列总结(一)

    本节目录 常用函数一:获取指定文件夹内所有文件 常用函数二:文件合并 常用函数三:将文件按时间划分 常用函数四:数据去重 写在前面 写代码也有很长时间了,总觉得应该做点什么有价值的事情,写代码初始阶段 ...

最新文章

  1. Vivado安装器件不全
  2. mysql 评论回复表设计_【数据库】评论回复表设计
  3. html用颜色区分不同区间数据_最新数据可视化指南
  4. PTA-1011——World Cup Betting
  5. Java容器解析——HashMap
  6. 2019第一季度海外市场手机出货量报告:华为、小米逆势增长
  7. 杭电5621 KK's Point
  8. python异常之EOFError: Ran out of input
  9. 线上四台机器同一时间全部 OOM,到底发生了什么?
  10. ACL'22 | 使用对比学习增强多标签文本分类中的k近邻机制
  11. C++动态连接库动态加载
  12. Go语言自学系列 | go常用命令
  13. 软件测试面试中项目介绍宝典
  14. cygwin安装top命令
  15. 计算机毕业论文提纲如何写,计算机毕业论文提纲怎么写
  16. Cloud E随笔-后端_piece3--实现登录功能
  17. 数据库完整性详细解释
  18. DLNA实现本地媒体服务器
  19. Jetpack Room基本用法
  20. 利用java编写网络聊天程序并加密信息

热门文章

  1. 思科设备三层交换配置路由实现互通
  2. 登录网络计算机提示用户名错误,局域网访问共享时提示登录失败:未知的用户名或错误密码 怎么回事...
  3. 如何检测新移动硬盘--HD Tune Pro硬盘工具
  4. 关于α测试与β测试的区别
  5. postMan中文修改
  6. 中职计算机课题申报,中职计算机教研课题怎么申报
  7. 虚拟机xp与Linux 【ping命令】
  8. 单片机的串行通讯就是排成一队走,并行就是排成一列走
  9. 原生js打印插件Print.js
  10. VMware Fusion 13 正式版终于来了