标签

Honeymoon - Thomas Ng

归档

近期文章

Our Visitor

008078
用户今天 : 13
合计查看 : 15787
谁是在线的 : 0
你的IP地址 : 40.77.167.28

Laravel12框架实现Helpers.php

本文章实现 Laravel12框架实现Helpers.php

不懂的可以评论或联系我邮箱:owen@owenzhang.com

著作权归OwenZhang所有。商业转载请联系OwenZhang获得授权,非商业转载请注明出处。

app/Providers/HelperServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        // 加载所有辅助函数
        foreach (glob(app_path('Helpers') . '/*.php') as $file) {
            require_once $file;
        }
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}

bootstrap/providers.php

<?php

return [
    App\Providers\AppServiceProvider::class,
    App\Providers\HelperServiceProvider::class,
];

app/Helpers/Helpers.php

    <?php

use Carbon\CarbonPeriod;

/**
 * @notes : 获取日期格式横坐标
 * @param int $day //天数,7,30,365
 * @return array
 * @author: OwenZhang
 * @time  : 2026/2/5 11:40
 */
if (!function_exists('getDateAxis')) {
    function getDateAxis(int $day): array
    {
        $endDate = now()->endOfDay();

        if ($day === 365) {
            // 生成过去12个月的月份
            $startDate = now()->subMonths(11)->startOfMonth();
            $period    = CarbonPeriod::create($startDate, '1 month', $endDate);

            return collect($period)->map(function ($date) {
                return $date->format('Ym');
            })->toArray();
        }

        // 生成天数
        $startDate = now()->subDays($day - 1)->startOfDay();
        $period    = CarbonPeriod::create($startDate, $endDate);

        return collect($period)->map(function ($date) {
            return $date->format('m.d');
        })->toArray();
    }
}

/**
 * @notes : 获取月的最后一天
 * @param string $yearMonth //202503
 * @return string
 * @author: OwenZhang
 * @time  : 2026/2/5 15:28
 */
if (!function_exists('getMonthLastDay')) {
    function getMonthLastDay(string $yearMonth)
    {
        $year    = substr($yearMonth, 0, 4);
        $month   = substr($yearMonth, 4, 2);
        $lastDay = date('Ymd', strtotime("{$year}-{$month}-01 +1 month -1 day"));

        return $lastDay;
    }
}

调用


public function test(int $day): array
{
    //横轴
   $xAxis = getDateAxis($day);
}

Buy me a cup of coffee :)

觉得对你有帮助,就给我打赏吧,谢谢!

微信赞赏码链接,点击跳转:

Laravel12框架实现Helpers.php插图

Tags: