1. 在 Laravel 项目的根目录下创建一个新的文件比如 app/Helpers.php
用于存放 Helper 函数。
2. 在名为 Helpers.php 的文件,定义你的 Helper 函数:
if (! function_exists('test_helper')) {
function test_helper() {
return 'This is a test helper function';
}
}
3. 在 composer.json 文件中添加:
"autoload": {
"files": [
"app/helpers.php"
]
},
4. 运行命令 composer dump-autoload,使 Composer 加载新的 Helper 函数文件。
定义好后,你就可以在 Laravel 应用的任何地方直接使用该 Helper 函数 test_helper()。
需要注意的是,这种方式是将 Helper 函数定义为一个自动加载的文件,而不是一个全局函数。这样可以确保在 Laravel 的整个生命周期中> 都能使用该函数,而不需要每次使用时手动引入。
记录个人在 Laravel
框架中常用函数
if (!function_exists('random_number')) {
/**
* 随机数字
* @param int $length 长度
* @return int
*/
function random_number(int $length = 6): int
{
$chars = str_repeat('0123456789', 3);
if ($length > 10) {
$chars = str_repeat($chars, $length);
}
$chars = str_shuffle($chars);
return (integer)substr($chars, 0, $length);
}
}
if (!function_exists('nullToString')) {
/**
* null 转 空字符串
* @param $str
* @return string
*/
function nullToString($str): string
{
if (gettype($str) == 'NULL') {
return '';
}
return $str;
}
}
if (!function_exists('get_oss_url')) {
/**
* 获取oss服务器静态文件地址
* @param string $fileUrl 文件
* @return string
*/
function get_oss_url(string $fileUrl): string
{
if (gettype($fileUrl) == "NULL") {
return '';
}
if (strpos($fileUrl, 'http') !== false) {
return $fileUrl;
}
return $fileUrl ? 'https://xxx.com' . $fileUrl : $fileUrl;
}
}
if (!function_exists('filter_array_null')) {
/**
* 过滤数组中的NULL
* @param array $arr 数组
* @return array 过滤后的数组
*/
function filter_array_null(array $arr): array
{
return collect($arr)->filter(function ($item) {
return !is_null($item);
})->all();
}
}
if (!function_exists('flatten')) {
/**
* 转化为同级的
* @param array|object $item
* @param array $user 用户数据
* @return array|object
*/
function flatten($item, array $user)
{
if (empty($user)) {
return $item;
}
foreach ($user as $key => $value) {
if (!isset($item[$key])) {
$item[$key] = $value;
}
}
return $item;
}
}