定制 caleb/laravel-practice 二次开发

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

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

caleb/laravel-practice

Composer 安装命令:

composer require caleb/laravel-practice

包简介

A Laravel practice development package, ready to use out of the box. It simplifies handling responses, filters, services, and exception management.

README 文档

README

A Laravel practice development package, ready to use out of the box. It simplifies handling responses, filters, services, and exception management.

Features

  • Standardized JSON Response: Unified API response format with request ID tracking
  • Query Filters: Elegant and reusable query filtering system
  • Service Layer: Base service class with exception handling capabilities
  • Exception Management: Comprehensive exception handling with localized messages
  • Model Standardization: Enhanced Eloquent models with standardized JSON serialization
  • Request Context: Automatic request ID generation and context management
  • Artisan Commands: Generate filters and services with custom commands

Requirements

  • PHP ^8.1
  • Laravel ^12.0
  • ext-json

Installation

Install the package via Composer:

composer require caleb/laravel-practice

The package will automatically register its service provider.

Configuration

Publish Language Files

php artisan vendor:publish --tag=practice-lang

Publish Stubs

php artisan vendor:publish --tag=practice-stubs

Usage

1. Response Trait

Use the Response trait in your controllers to standardize API responses:

<?php

namespace App\Http\Controllers;

use Caleb\Practice\Response;
use Illuminate\Http\Controller;

class UserController extends Controller
{
    use Response;
    
    public function index()
    {
        $users = User::all();
        return $this->success($users);
    }
    
    public function store(Request $request)
    {
        try {
            $user = User::create($request->validated());
            return $this->success($user);
        } catch (Exception $e) {
            return $this->error('Failed to create user', 422);
        }
    }
}

Response format:

{
    "code": 200,
    "msg": "success",
    "data": {...},
    "request_id": "uuid-string"
}

2. Query Filters

Create a filter class:

php artisan practice:make:filter UserFilter

Define your filter:

<?php

namespace App\Filters;

use Caleb\Practice\QueryFilter;

class UserFilter extends QueryFilter
{
    public function name($name)
    {
        $this->query->where('name', 'like', "%{$name}%");
    }
    
    public function email($email)
    {
        $this->query->where('email', $email);
    }
}

Use in your model:

<?php

namespace App\Models;

use Caleb\Practice\Standardization;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use Standardization;
}

Apply filters in controller:

public function index(UserFilter $filter)
{
    $users = User::filter($filter)->paginate();
    return $this->success($users);
}

3. Service Layer

Create a service class:

php artisan practice:make:service UserService

Define your service:

<?php

namespace App\Services;

use Caleb\Practice\Service;
use App\Models\User;

class UserService extends Service
{
    public function createUser(array $data)
    {
        if (User::where('email', $data['email'])->exists()) {
            $this->throwAppException('Email already exists', 422);
        }
        
        return User::create($data);
    }
    
    public function getUserById(int $id)
    {
        $user = User::find($id);
        
        if (!$user) {
            $this->throwAppException('User not found', 404);
        }
        
        return $user;
    }
}

Use in controller:

public function store(Request $request)
{
    $user = UserService::instance()->createUser($request->validated());
    return $this->success($user);
}

4. Model Standardization

Use the Standardization trait in your models:

<?php

namespace App\Models;

use Caleb\Practice\Standardization;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use Standardization;
    
    protected $casts = [
        'settings' => 'array',
        'created_at' => 'datetime',
    ];
}

Benefits:

  • JSON serialization with JSON_UNESCAPED_UNICODE flag
  • Dynamic per_page from request parameters
  • Built-in filter scope for query filtering

5. Exception Handling

The package provides automatic exception handling with localized messages:

  • ValidationException: Returns 422 with validation errors
  • AuthenticationException: Returns 401 with error message
  • PracticeException: Returns custom error code and message
  • ModelNotFoundException: Returns 404 with "Resource not found" message
  • ThrottleRequestsException: Returns 429 with rate limit message

Custom exceptions:

// Application exceptions (logged as DEBUG level)
$this->throwAppException('Custom error message', 422, $additionalData);

// External service exceptions (logged normally)
$this->throwExternalAppException('External service error', 503);

6. Request Context

The package automatically adds a unique request ID to each request context and includes it in all responses. This helps with request tracking and debugging.

Middleware

The package automatically registers the AddContext middleware which:

  • Generates a unique UUID for each request
  • Stores it in Laravel's Context
  • Includes it in all JSON responses

Localization

The package supports multiple languages. Currently included:

English (en):

  • System success/error messages
  • Resource not found messages

Chinese (zh-CN):

  • 系统成功/错误消息
  • 资源未找到消息

You can publish and customize these messages:

php artisan vendor:publish --tag=practice-lang

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is open-sourced software licensed under the MIT license.

Author

Keywords

  • Laravel
  • Response
  • Request ID
  • Service
  • Filter
  • Exception Handler
  • Model Standardization

caleb/laravel-practice 适用场景与选型建议

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

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

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

围绕 caleb/laravel-practice 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-12-18