承接 sgflores/cruder 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

sgflores/cruder

最新稳定版本:v1.0.0

Composer 安装命令:

composer require sgflores/cruder

包简介

A comprehensive CRUD service package

README 文档

README

License: MIT PHP Version Laravel Version

A powerful, feature-rich CRUD service package for Laravel applications built on SOLID principles and design patterns. Provides comprehensive database operations with advanced features like caching, query logging, column validation, export capabilities, and more.

🚀 Key Features

  • Complete CRUD Operations - Create, Read, Update, Delete with full validation
  • Bulk Operations - Efficient bulk create, update, and delete operations
  • Advanced Filtering & Search - Column-based filtering, sorting, and text search
  • Search Strategy System - Pluggable search strategies for custom search implementations
  • Export Functionality - CSV, JSON, and custom export formats
  • Filter Helpers - One-line helpers for common filter patterns such as between ranges
  • Query Caching - Built-in query caching with configurable lifetime
  • Performance Monitoring - Query logging and slow query detection
  • Column Validation - Secure column validation for all operations
  • Virtual Filters - Safely expose computed filter columns via getCustomFilterColumns()
  • Event System - Extensible event system for custom business logic
  • Trait-Based Configuration - Type-safe, IDE-friendly configuration system
  • Audit Trail - Automatic tracking of record changes (created_by, updated_by, deleted_by)

📋 Requirements

  • PHP ^8.1
  • Laravel ^10.0|^11.0|^12.0
  • Illuminate Support ^10.0|^11.0|^12.0
  • Illuminate Database ^10.0|^11.0|^12.0
  • Illuminate Validation ^10.0|^11.0|^12.0
  • Illuminate Pagination ^10.0|^11.0|^12.0

📦 Installation

1. Install via Composer

composer require sgflores/cruder

2. Publish Configuration (Optional)

php artisan vendor:publish --provider="SgFlores\Cruder\CruderServiceProvider" --tag="cruder-config"

3. Service Provider (Auto-discovered)

The package will be automatically discovered by Laravel.

🎯 Quick Start

1. Create Your Service

<?php

namespace App\Services;

use SgFlores\Cruder\BaseCrudService;
use SgFlores\Cruder\Services\EventService;
use SgFlores\Cruder\Services\ValidationService;
use App\Models\User;

class UserService extends BaseCrudService
{
    public function __construct(
        User $user,
        EventService $eventService,
        ValidationService $validationService
    ) {
        parent::__construct($user, $eventService, $validationService);
    }
    
    // Override configuration methods as needed
    public function getDirectTextSearchColumns(): array
    {
        return ['name', 'email'];
    }
    
    public function getDirectFilterableColumns(): array
    {
        return ['status', 'department_id'];
    }
    
    public function getDirectSortableColumns(): array
    {
        return ['name', 'email', 'created_at'];
    }
    
    public function isAuditTrailEnabled(): bool
    {
        return true;
    }
}

💡 Configuration: The service uses a trait-based configuration system. See CONFIGURATION.md for all available configuration methods and examples.

2. Basic Usage

// Find all users with filtering and pagination
$users = $userService->findAll([
    'search' => 'john',
    'status' => 'active',
    'sort_by' => 'name',
    'sort_direction' => 'asc',
    'per_page' => 10,
    'page' => 1
]);

// Find user by ID and load department relation (resource-aware)
$user = $userService->findById(1, ['department']); // returns Model|JsonResource|null

// Find raw model (no resource transformation) for policy checks
$rawUser = $userService->findByIdRaw(1, ['department']); // returns ?Model

// Create user (returns Model|JsonResource)
$user = $userService->create([
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);

// Update user (returns Model|JsonResource|null)
$user = $userService->update(1, [
    'name' => 'John Smith'
]);

// Delete user
$userService->delete(1);

// Bulk operations
$userService->bulkCreate([
    ['name' => 'User 1', 'email' => 'user1@example.com'],
    ['name' => 'User 2', 'email' => 'user2@example.com']
]);

3. Between Filter Helper

BaseReaderService ships with a convenience helper for assembling range filters without hand-writing the advanced filter structure:

$filters = [
    'created_from' => '2025-01-01',
    'created_to'   => '2025-01-31',
];

$this->mergeBetweenFilter(
    $filters,
    'orders.created_at', // actual database column
    'created_from',      // input key for the lower bound
    'created_to',        // input key for the upper bound
    'Y-m-d'              // optional Carbon format
);

// $filters now contains:
// [
//     'orders.created_at' => [
//         'operator' => 'between',
//         'value'    => ['2025-01-01', '2025-01-31'],
//     ],
// ]

// Resulting SQL fragment
// where `orders`.`created_at` between '2025-01-01' and '2025-01-31'

📝 Note: For export functionality, you'll need to extend BaseReaderService with SearchService and ExportService injected. See Examples/README.md for complete examples.

4. Search Strategies

Create custom search implementations for complex reporting and analytics using the strategy pattern.

Key Features:

  • Custom Search Strategies - Pluggable strategies
  • Query Type Flexibility - Support both Eloquent Builder and QueryBuilder
  • Proper Service Injection - Extend BaseReaderService with SearchService injected

Example Strategy Implementation:

class TopOrdersStrategy implements SearchStrategyInterface
{
    public static function key(): string
    {
        return 'top_orders';
    }
    
    public function search(Builder|QueryBuilder|null $query, array $filters, array $config = []): Builder|QueryBuilder
    {
        return $query->orderBy('total_amount', 'desc');
    }
}

Usage:

// Register strategy
$this->searchService->addStrategy(TopOrdersStrategy::key(), new TopOrdersStrategy());

// Use in queries
$results = $this->findAll(['strategies' => TopOrdersStrategy::key()]);

Complete Example: See Examples/SalesReportService.php for full implementation.

📚 Documentation

📖 Available Examples

Quick Reference:

See Examples/README.md for comprehensive documentation.

🧪 Testing

composer test              # Run test suite
composer test-coverage     # Run with coverage

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

👨‍💻 Author

sgflores

🙏 Acknowledgments

Built with ❤️ for the Laravel community using:

统计信息

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

GitHub 信息

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

其他信息

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