webmonks/laravel-api-modules

SOLID principle, modular API code generator for Laravel

v1.14 2025-09-11 11:57 UTC

This package is auto-updated.

Last update: 2025-09-11 12:02:54 UTC


README

Latest Version on Packagist Total Downloads MIT Licensed Laravel PHP

A powerful SOLID-principle Laravel modular code generator specifically designed for API-first projects.

Transform your Laravel development with intelligent module generation that creates clean, maintainable, and scalable API architectures following industry best practices.

โœจ Why Laravel API Modules?

๐ŸŽฏ Built for API Excellence

  • Zero Frontend Concerns: Pure API-focused architecture
  • SOLID Principles: Every generated component follows dependency injection and single responsibility
  • Repository Pattern: Clean separation of data access logic
  • Service Layer: Business logic abstraction for better testability

โšก Intelligent Generation

  • Complete Module Scaffold: Controllers, Models, Services, Repositories, Interfaces, Requests, Migrations, Tests
  • Two Generation Modes: Simple list APIs or full CRUD resources
  • Auto-Wired Dependencies: Everything is pre-configured and ready to use
  • Smart Naming: Consistent naming conventions across all components

๐Ÿ”ง Developer Experience

  • One Command Setup: Generate complete modules with a single artisan command
  • Zero Configuration: Works out of the box with sensible defaults
  • Full Customization: Publish and modify all templates to match your standards
  • IDE Friendly: Proper type hints and interfaces for better development experience

๐Ÿ“ฆ Installation

Requirements

Component Version
PHP ^7.4 | ^8.0 | ^8.1 | ^8.2 | ^8.3
Laravel ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0

Quick Install

# Install the package
composer require webmonks/laravel-api-modules

Configuration (Optional)

# Publish configuration for customization
php artisan vendor:publish --tag=laravel-api-modules-config

# Publish stub templates for team-specific modifications
php artisan vendor:publish --tag=laravel-api-modules-stubs

That's it! The package is auto-discovered and ready to use. ๐ŸŽ‰

๐Ÿš€ Quick Start

Generate Your First Module

# Create a simple list-only API module
php artisan make:module Blog

# Create a full CRUD resource module
php artisan make:module Product --resource

Remove Modules Safely

# Preview what would be removed (dry-run)
php artisan remove:module Blog --preview

# Remove with interactive confirmation
php artisan remove:module Blog

# Remove with automatic backup (default)
php artisan remove:module Product

# Remove without confirmations
php artisan remove:module Product --force

# Remove without creating backup
php artisan remove:module Product --force --no-backup

What Gets Generated?

Simple Module (php artisan make:module Blog)

app/Modules/Blog/
โ”œโ”€โ”€ Controllers/BlogController.php     # List endpoint only
โ”œโ”€โ”€ Models/Blog.php                    # Eloquent model with traits
โ”œโ”€โ”€ Services/BlogService.php          # Business logic layer
โ”œโ”€โ”€ Repositories/BlogRepository.php   # Data access layer
โ”œโ”€โ”€ Request/ListBlogRequest.php       # Validation for list endpoint
โ””โ”€โ”€ routes.php                        # Auto-registered routes

app/Core/
โ”œโ”€โ”€ Interfaces/BlogRepositoryInterface.php  # Repository contract
โ””โ”€โ”€ Providers/RepositoryServiceProvider.php # Auto-generated bindings

database/migrations/
โ””โ”€โ”€ xxxx_xx_xx_xxxxxx_create_blogs_table.php

tests/
โ”œโ”€โ”€ Feature/Modules/Blog/BlogFeatureTest.php
โ””โ”€โ”€ Unit/Modules/Blog/BlogUnitTest.php

Resource Module (php artisan make:module Product --resource)

app/Modules/Product/
โ”œโ”€โ”€ Controllers/ProductController.php          # Full CRUD endpoints
โ”œโ”€โ”€ Models/Product.php                        # Eloquent model
โ”œโ”€โ”€ Services/ProductService.php               # Complete business logic
โ”œโ”€โ”€ Repositories/ProductRepository.php        # Full data operations
โ”œโ”€โ”€ Request/
โ”‚   โ”œโ”€โ”€ ListProductRequest.php               # List validation
โ”‚   โ”œโ”€โ”€ ViewProductRequest.php               # View validation
โ”‚   โ”œโ”€โ”€ CreateProductRequest.php             # Create validation
โ”‚   โ”œโ”€โ”€ UpdateProductRequest.php             # Update validation
โ”‚   โ””โ”€โ”€ DeleteProductRequest.php             # Delete validation
โ””โ”€โ”€ routes.php                               # All CRUD routes

Your Project Structure

After generating your first module, your Laravel application will have this enhanced structure:

app/
โ”œโ”€โ”€ Core/                                    # ๐Ÿ—๏ธ Architecture Layer
โ”‚   โ”œโ”€โ”€ Interfaces/                         # Repository contracts
โ”‚   โ”‚   โ””โ”€โ”€ BlogRepositoryInterface.php
โ”‚   โ”œโ”€โ”€ Providers/                          # Auto-generated service bindings
โ”‚   โ”‚   โ””โ”€โ”€ RepositoryServiceProvider.php
โ”‚   โ”œโ”€โ”€ Services/                           # Shared base services
โ”‚   โ”‚   โ””โ”€โ”€ BaseService.php
โ”‚   โ””โ”€โ”€ Traits/                             # Reusable functionality
โ”‚       โ”œโ”€โ”€ ApiResponser.php               # Standard API responses
โ”‚       โ”œโ”€โ”€ ActivityLogHelper.php          # Model activity tracking
โ”‚       โ”œโ”€โ”€ PdfGeneratorTrait.php          # PDF generation
โ”‚       โ”œโ”€โ”€ SmsSender.php                  # SMS notifications
โ”‚       โ””โ”€โ”€ UserUpdater.php                # Auto user tracking
โ”œโ”€โ”€ Helpers/                                # ๐Ÿ”ง Utility Functions
โ”‚   โ””โ”€โ”€ AutoloadFiles/                     # Auto-loaded helpers
โ”‚       โ””โ”€โ”€ string_helpers.php
โ”œโ”€โ”€ Models/                                 # ๐Ÿ—ƒ๏ธ Shared Models
โ”‚   โ””โ”€โ”€ BaseModel.php                      # Enhanced base model
โ””โ”€โ”€ Modules/                               # ๐ŸŽฏ Your API Modules
    โ””โ”€โ”€ Blog/
        โ”œโ”€โ”€ Controllers/BlogController.php
        โ”œโ”€โ”€ Models/Blog.php
        โ”œโ”€โ”€ Repositories/BlogRepository.php
        โ”œโ”€โ”€ Services/BlogService.php
        โ”œโ”€โ”€ Request/ListBlogRequest.php
        โ””โ”€โ”€ routes.php                     # Auto-discovered routes

config/
โ””โ”€โ”€ laravel-api-modules.php               # Package configuration

database/migrations/
โ””โ”€โ”€ 2024_01_01_000000_create_blogs_table.php

tests/
โ”œโ”€โ”€ Feature/Modules/Blog/BlogFeatureTest.php
โ””โ”€โ”€ Unit/Modules/Blog/BlogUnitTest.php

๐Ÿ”ง Core Features

๐Ÿ—‘๏ธ Safe Module Removal

Complete cleanup with safety checks! The package provides:

  • ๐Ÿ” Preview Mode: See exactly what files will be removed before deletion
  • ๐Ÿ“ฆ Automatic Backup: Creates timestamped backups before removal (optional)
  • โš ๏ธ Multi-stage Confirmations: Multiple safety prompts prevent accidental deletion
  • ๐Ÿงน Complete Cleanup: Removes all related files (controllers, models, tests, migrations, interfaces)
  • ๐Ÿ”„ Repository Binding Cleanup: Automatically cleans up service provider bindings
  • ๐Ÿšจ Security Validation: Prevents path traversal and validates module names
# Safe removal with all protections
php artisan remove:module UserProfile

# Quick preview of what would be removed
php artisan remove:module UserProfile --preview

# Force removal without confirmations
php artisan remove:module UserProfile --force --no-backup

๐Ÿ”— Automatic Repository Binding

Zero Configuration Required! The package automatically:

  • Generates RepositoryServiceProvider.php to bind interfaces to implementations
  • Registers the provider in Laravel's service container
  • Creates proper dependency injection for all your modules
// This happens automatically - no manual binding needed!
$this->app->bind(
    BlogRepositoryInterface::class,
    BlogRepository::class
);

๐Ÿท๏ธ Smart Traits System

The package includes battle-tested traits for common API functionality:

Trait Purpose Auto-Included
ApiResponser Consistent API response format โœ… Required
ActivityLogHelper Track model changes and actions โš™๏ธ Optional
PdfGeneratorTrait Generate PDFs from Blade templates โš™๏ธ Optional
SmsSender Send SMS via Twilio with logging โš™๏ธ Optional
UserUpdater Auto-manage created_by, updated_by fields โš™๏ธ Optional

๐Ÿ”„ Helper Autoloader

Drop any PHP helper files into app/Helpers/AutoloadFiles/ and they're automatically available throughout your application:

// app/Helpers/AutoloadFiles/api_helpers.php
function transform_response($data, $message = 'Success') {
    return ['data' => $data, 'message' => $message];
}

// Available everywhere in your app automatically!
return transform_response($users, 'Users retrieved successfully');

โš™๏ธ Configuration

The package works perfectly with zero configuration, but offers extensive customization options:

๐Ÿ“‹ View Configuration Options
// config/laravel-api-modules.php
return [
    // Directory Structure
    'modules_dir' => 'app/Modules',
    'core_interfaces_dir' => 'app/Core/Interfaces',
    
    // Namespaces
    'namespace' => 'App\\Modules',
    'interface_namespace' => 'App\\Core\\Interfaces',
    
    // Base Classes
    'enable_base_model' => true,        // Generate BaseModel
    'enable_base_service' => true,      // Generate BaseService
    'model_extends_base' => 'BaseModel',
    
    // Code Generation
    'generate_migration' => true,       // Create migrations
    'generate_tests' => true,          // Create test files
    'auto_discover_routes' => true,    // Auto-register routes
    
    // Traits Configuration
    'base_model_traits' => [
        'ApiResponser' => true,         // Required
        'ActivityLogHelper' => true,   // Optional
        'PdfGeneratorTrait' => true,   // Optional
        'SmsSender' => true,           // Optional
        'UserUpdater' => true,         // Optional
    ],
];

๐Ÿ’ก Usage Examples

Example 1: Blog API Module

# Generate a simple blog list API
php artisan make:module Blog

# Remove the blog module safely (with backup)
php artisan remove:module Blog

Generated controller will have a clean, testable structure:

// app/Modules/Blog/Controllers/BlogController.php
class BlogController extends Controller
{
    protected $blogService;

    public function __construct(BlogService $blogService)
    {
        $this->blogService = $blogService; // Auto-injected
    }

    public function list(ListBlogRequest $request)
    {
        $response = $this->blogService->listBlogs($request->validated());
        return $this->successResponse(
            $response, 
            'Blogs retrieved successfully', 
            Response::HTTP_OK
        );
    }
}

Example 2: Full CRUD Product API

# Generate a complete product management API
php artisan make:module Product --resource

# Preview what would be removed before deletion
php artisan remove:module Product --preview

# Remove with force (skip confirmations)
php artisan remove:module Product --force

This creates a full API with endpoints:

  • GET /api/products - List products with filtering
  • GET /api/products/{id} - Get single product
  • POST /api/products - Create new product
  • PUT /api/products/{id} - Update product
  • DELETE /api/products/{id} - Delete product

Example 3: Custom Helper Integration

// app/Helpers/AutoloadFiles/product_helpers.php
function calculate_discount($original_price, $discount_percent) {
    return $original_price * (1 - $discount_percent / 100);
}

function format_currency($amount) {
    return '$' . number_format($amount, 2);
}
// Use anywhere in your application
$discounted_price = calculate_discount($product->price, 15);
$formatted_price = format_currency($discounted_price);

๐Ÿ”ง Advanced Customization

Custom Stub Templates

Publish stubs and modify them to match your team's conventions:

php artisan vendor:publish --tag=laravel-api-modules-stubs

Edit any stub in stubs/laravel-api-modules/ to customize generated code:

// stubs/laravel-api-modules/controller.stub
class {{model}}Controller extends Controller
{
    // Your custom controller template
    // Add your standard methods, middleware, etc.
}

Extending Base Classes

The generated BaseModel and BaseService can be extended with your common functionality:

// app/Models/BaseModel.php - Auto-generated, customize as needed
abstract class BaseModel extends Model
{
    use ApiResponser, ActivityLogHelper, UserUpdater;
    
    // Add your common model methods here
    public function scopeActive($query) {
        return $query->where('is_active', true);
    }
}

๐Ÿงช Testing

The package generates comprehensive test files for each module:

// tests/Feature/Modules/Blog/BlogFeatureTest.php
class BlogFeatureTest extends TestCase
{
    public function test_can_list_blogs()
    {
        $response = $this->getJson('/api/blogs');
        $response->assertStatus(200)
                ->assertJsonStructure(['data', 'message']);
    }
}

Run tests for your modules:

# Run all tests
php artisan test

# Run specific module tests
php artisan test tests/Feature/Modules/Blog/
php artisan test tests/Unit/Modules/Blog/

๐Ÿ“š Documentation

Complete Guides

Resources

๐Ÿค Contributing

We welcome contributions from the community! Whether it's:

  • ๐Ÿ› Bug Reports: Found an issue? Let us know!
  • ๐Ÿ’ก Feature Requests: Have ideas for improvements?
  • ๐Ÿ”ง Code Contributions: Submit pull requests with enhancements
  • ๐Ÿ“– Documentation: Help improve our guides and examples

See our Contributing Guidelines for details.

๐Ÿ† Credits

Laravel API Modules is crafted with โค๏ธ by WebMonks Technologies

Built With

  • Laravel - The PHP Framework for Web Artisans
  • PHP - A popular general-purpose scripting language
  • SOLID Principles - Object-oriented design principles
  • Repository Pattern - Clean architecture pattern

๐Ÿ“„ License

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

๐ŸŒŸ Star this repository if it helped you!

Made with โค๏ธ for the Laravel community

โญ Give us a star โ€ข ๐Ÿ“ฆ View on Packagist โ€ข ๐Ÿ› Report Issues