lambertns/laravel-make-service 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

lambertns/laravel-make-service

最新稳定版本:v1.2.0

Composer 安装命令:

composer require lambertns/laravel-make-service

包简介

Adds `php artisan make:service` command to generate service classes with optional automatic controller injection using PHP 8+ property promotion.

README 文档

README

A Laravel package that adds a make:service command to generate service classes with optional dependency injection into controllers.

Why Use Services?

Controllers can quickly become bloated with business logic, making them hard to maintain and test. Services help by:

  • 🔧 Separate Concerns: Move business logic out of controllers into dedicated service classes
  • 📉 Reduce Controller Complexity: Keep controllers thin and focused on HTTP handling
  • ♻️ Reusability: Share business logic across multiple controllers or queue jobs
  • 🧪 Testability: Easier to unit test business logic in isolation
  • 📚 Maintainability: Organized code that's easier to read and maintain

Example Problem

Without Services (Fat Controller):

class OrderController extends Controller
{
    public function store(Request $request)
    {
        // Validation
        $validated = $request->validate([...]);
        
        // Business logic
        $order = Order::create($validated);
        
        // Payment processing
        $payment = PaymentGateway::charge(...);
        $order->update(['payment_id' => $payment->id]);
        
        // Notification logic
        Mail::to($order->user)->send(new OrderConfirmation($order));
        
        // Inventory management
        foreach ($order->items as $item) {
            $item->product->decrement('stock', $item->quantity);
        }
        
        // More logic...
        
        return response()->json($order, 201);
    }
}

With Services (Clean Controller):

class OrderController extends Controller
{
    public function __construct(
        private OrderService $orderService
    ) {}
    
    public function store(Request $request)
    {
        $order = $this->orderService->createOrder($request->validated());
        
        return response()->json($order, 201);
    }
}

Features

  • 🚀 Generate service classes with the php artisan make:service command
  • 💉 Automatically inject services into controllers using the --controller option
  • 📝 Use PHP 8+ constructor property promotion for clean dependency injection
  • 🎯 Add multiple methods to services using the --methods option
  • ✅ Follows Laravel conventions and best practices

Installation

You can install the package via Composer:

composer require lambertns/laravel-make-service

That's it! The package will automatically register the service provider.

Quick Start

Let's say you have a controller with lots of business logic and want to refactor it:

  1. Create a service to extract the logic:
php artisan make:service PaymentService --controller=OrderController --methods="process,refund,cancel"
  1. Your service is created and automatically injected:
// app/Http/Services/PaymentService.php
class PaymentService
{
    public function process($order) { /* ... */ }
    public function refund($order) { /* ... */ }
    public function cancel($order) { /* ... */ }
}
  1. Use it in your controller:
// app/Http/Controllers/OrderController.php
class OrderController extends Controller
{
    public function __construct(
        private PaymentService $paymentService
    ) {}
    
    public function store(Request $request)
    {
        // Now your business logic is in the service
        $order = $this->paymentService->process($request->validated());
        
        return response()->json($order, 201);
    }
}

Usage

Basic Service Creation

Create a simple service:

php artisan make:service UserService

This will create app/Http/Services/UserService.php:

<?php

namespace App\Http\Services;

class UserService
{
    // Add your methods here
}

Create Service with Methods

Add methods to your service:

php artisan make:service PaymentService --methods="pay,refund,cancel"

This creates a service with three methods:

<?php

namespace App\Http\Services;

class PaymentService
{
    /**
     *pay()
     */
    public function pay()
    {
        // TODO: implement pay()
    }

    /**
     *refund()
     */
    public function refund()
    {
        // TODO: implement refund()
    }

    /**
     *cancel()
     */
    public function cancel()
    {
        // TODO: implement cancel()
    }
}

Auto-Inject into Controller

Automatically inject the service into a controller:

php artisan make:service PaymentService --controller=AuthController

This will:

  1. Create app/Http/Services/PaymentService.php
  2. Add use App\Http\Services\PaymentService; to the controller
  3. Add constructor injection with property promotion:
<?php

namespace App\Http\Controllers;

use App\Http\Services\PaymentService;

class AuthController
{
    public function __construct(
        private PaymentService $paymentService
    ) {
    }
}

Inject into Multiple Controllers

Inject the service into multiple controllers at once (comma-separated):

php artisan make:service PaymentService --controller=AuthController,UserController,OrderController

This will inject the service into all three controllers and show a summary:

✓ Injected into AuthController
✓ Injected into UserController
✓ Injected into OrderController
Summary: 3 successful, 0 failed

Inject into Existing Controller

You can also add services to controllers that already have dependencies:

php artisan make:service NotificationService --controller=UserController

If the controller already has a constructor with dependencies, the new service will be added:

public function __construct(
    private UserService $userService,
    private NotificationService $notificationService  // ← Added automatically
) {
}

Command Options

Option Description Example
--controller Controller(s) to inject into (comma-separated for multiple) --controller=AuthController,UserController
--methods Comma-separated list of method names --methods="index,store,update"
--force Overwrite existing service --force

Examples

Create a service with multiple methods and inject into multiple controllers:

php artisan make:service OrderService --methods="create,update,cancel" --controller=OrderController,CheckoutController

This will create the OrderService with three methods and inject it into both controllers.

Use in nested namespaces:

php artisan make:service Admin\UserService --controller=Admin\UserController

Requirements

  • PHP >= 8.1
  • Laravel >= 10.0
  • Illuminate/Support >= 10.0
  • Illuminate/Console >= 10.0
  • Illuminate/Filesystem >= 10.0

Features

Constructor Property Promotion

This package uses PHP 8's constructor property promotion for clean dependency injection:

public function __construct(
    private PaymentService $paymentService
) {
}

This eliminates the need for separate property declarations and manual assignment.

Smart Use Statement Insertion

The package intelligently adds use statements in the correct location:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Services\PaymentService;  // ← Added automatically

class AuthController
{
    // ...
}

Troubleshooting

Service not being injected?

  1. Make sure the controller exists
  2. Check that the controller has a valid namespace
  3. Verify the controller file is writable

License

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

Contributing

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

Support

If you encounter any issues or have questions, please open an issue on GitHub.

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-26