定制 mainul/custom-helpers 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mainul/custom-helpers

Composer 安装命令:

composer require mainul/custom-helpers

包简介

A Laravel package providing helper functions for API and web responses

README 文档

README

A Laravel package providing comprehensive helper functions for handling API and web responses, authentication, code generation, date formatting, file uploads, and more.

Requirements

  • PHP >= 8.2
  • Laravel 11.x or 12.x

Installation

Step 1: Install via Composer

composer require mainul/custom-helpers

Step 2: Publish Configuration (Optional)

Publish the configuration file to customize package settings:

php artisan vendor:publish --tag=helper-functions-config

This will create a config/helper-functions.php file where you can customize:

  • Route settings (prefix, middleware)
  • Default error messages
  • API detection patterns
  • And more

Step 3: Publish Routes (Optional)

If you want to customize the routes, publish the route files:

php artisan vendor:publish --tag=helper-functions-routes

This will create:

  • routes/helper-functions-web.php
  • routes/helper-functions-api.php

You can then update the routes in these files and disable the package routes in config/helper-functions.php:

'routes' => [
    'web' => [
        'enabled' => false, // Disable package web routes
    ],
    'api' => [
        'enabled' => false, // Disable package API routes
    ],
],

Configuration

After publishing the config file, you can customize the package in config/helper-functions.php:

Routes Configuration

'routes' => [
    'web' => [
        'enabled' => true,              // Enable/disable web routes
        'prefix' => null,               // Route prefix
        'middleware' => ['web'],        // Middleware groups
    ],
    'api' => [
        'enabled' => true,              // Enable/disable API routes
        'prefix' => 'api',              // Route prefix
        'middleware' => ['api'],        // Middleware groups
    ],
],

CustomHelper Configuration

'custom_helper' => [
    'default_error_message' => 'Something went wrong. Please try again.',
    'no_data_message' => 'No Data found.',
    'default_success_message' => 'Operation completed successfully.',
    'api_guard' => 'sanctum',           // Auth guard for API
    'default_guard' => null,            // Default auth guard
],

Usage

Using the CustomHelper Class

use Mainul\CustomHelperFunctions\Helpers\CustomHelper;

// Return data for web or API
return CustomHelper::returnDataForWebOrApi($data, 'users.index', $errorMessage);

// Return success message
return CustomHelper::returnSuccessMessage('User created successfully');

// Check authentication
if (CustomHelper::authCheck()) {
    $user = CustomHelper::loggedUser();
}

// Generate code (OTP)
$otp = CustomHelper::generateCode(6, 'number');

// Get session code
$sessionCode = CustomHelper::getSessionCode('mobile_123');

Available Methods

Response Methods

Method Description
returnDataForWebOrApi($data, $viewPath, $jsonErrorMessage, $isForRender, $isReturnBack, $successMsg) Return JSON for API/AJAX or view for web requests
returErrorMessage($message, $customMsg) Return error response for API or redirect back with error for web
returnSuccessMessage($message) Return success response for API or redirect back with success for web
returnRedirectWithMessage($route, $messageType, $message) Redirect to route with message (handles API/AJAX/web)

Request Detection Methods

Method Description
isApiRequest() Check if current request is an API request
isAjax() Check if current request is an AJAX request
wantsJsonResponse() Check if request wants JSON response (API or AJAX)

Authentication Methods

Method Description
authCheck() Check if user is authenticated (uses sanctum for API, default guard for web)
loggedUser() Get the currently logged-in user

Code Generation Methods

Method Description
generateCode($length, $type) Generate code - supports number, alpha, or random (alphanumeric)
generateSessionCode($length, $type, $sessionKey) Generate and store code in session/cache
getSessionCode($sessionKey) Retrieve generated code from session/cache

Date & Time Methods

Method Description
showDate($date) Format date as d-m-Y (e.g., 25-12-2024)
showTime($date) Format time as g:i A (e.g., 3:30 PM)
showDateTime($date) Format as d-m-Y g:i A (e.g., 25-12-2024 3:30 PM)
showDateTime24Hours($date) Format as d-m-Y H:i (e.g., 25-12-2024 15:30)
showDateForBlogType($date) Format as F d, Y (e.g., December 25, 2024)
dateWithTime($date) Format as Y-m-d H:i
currentDateWithTime() Get current date and time as Y-m-d H:i
getDurationAmongTwoDates($startDate, $endDate, $durationUnit, $isEndDateIsCurrentDate) Calculate duration between dates (years/months/days)
differTime($start, $end, $info) Get human-readable time difference

File Methods

Method Description
getFileExtension($file) Get file extension
getFileType($file) Get file MIME type
fileUpload($fileObject, $directory, $nameString, $modelFileUrl) Upload file to specified directory
fileUploadByBase64($base64String, $imageDirectory, $imageNameString, $modelFileUrl) Upload file from base64 string

Artisan Command Methods

Method Description
startQueueWorkManuallyByArtisanCommand() Manually process the queue
clearRouteCache() Clear route cache
CacheRoute() Cache routes
optimizeClear() Clear all optimizations
clearCache() Clear application cache

Controller Methods (CustomHelperController)

Route Method Description
symlink() Create storage symbolic link
optimizeReset() Clear all optimizations and return output
phpinfo() Display PHP information

Adding Custom Routes

Option 1: Edit Package Routes Directly (Not Recommended)

Edit src/routes/web.php or src/routes/api.php:

use Illuminate\Support\Facades\Route;
use Mainul\CustomHelperFunctions\Helpers\CustomHelper;

Route::get('/your-route', function () {
    // Your logic here
});

Option 2: Publish and Customize Routes (Recommended)

  1. Publish routes:
php artisan vendor:publish --tag=helper-functions-routes
  1. Edit published routes in routes/helper-functions-web.php or routes/helper-functions-api.php

  2. Disable package routes in config/helper-functions.php:

'routes' => [
    'web' => ['enabled' => false],
    'api' => ['enabled' => false],
],
  1. Load your custom routes in app/Providers/AppServiceProvider.php:
public function boot()
{
    $this->loadRoutesFrom(base_path('routes/helper-functions-web.php'));
    $this->loadRoutesFrom(base_path('routes/helper-functions-api.php'));
}

Optional Dependencies

The package works with these optional packages:

  • brian2694/laravel-toastr - For flash messages (optional)

If this package is not installed, the package will skip the related functionality.

License

MIT

Support

For issues and feature requests, please use the GitHub issue tracker.

mainul/custom-helpers 适用场景与选型建议

mainul/custom-helpers 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 88 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 12 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「response」 「helper」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mainul/custom-helpers 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mainul/custom-helpers 我们能提供哪些服务?
定制开发 / 二次开发

基于 mainul/custom-helpers 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 88
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-22