Skip to content

Grazulex/laravel-arc

Repository files navigation

Laravel Arc

Laravel Arc

Generate modern, type-safe Data Transfer Objects (DTOs) in Laravel from clean YAML definitions β€” with automatic validation, nested support, and fluent collection handling.

Latest Version Total Downloads License PHP Version Laravel Version Tests Code Style

Overview

Laravel Arc is a powerful Laravel package that simplifies Data Transfer Object (DTO) management through YAML-driven generation. Define your DTOs in simple YAML files and let Laravel Arc generate type-safe, validated PHP classes with automatic property access and comprehensive collection support.

Think of it as Laravel API Resources, but with stronger typing, automatic validation, and generated from YAML definitions.

πŸ—οΈ Architecture

graph TD
    A[YAML Definition] --> B[DTO Generator]
    B --> C[Generated DTO Class]
    
    A --> D[Field Types]
    A --> E[Transformers]
    A --> F[Validation Rules]
    A --> G[Behavioral Traits]
    
    C --> H[Functional Traits]
    H --> I[ValidatesData]
    H --> J[ConvertsData]
    H --> K[DtoUtilities]
    
    G --> L[HasTimestamps]
    G --> M[HasUuid]
    G --> N[HasSoftDeletes]
    G --> O[HasVersioning]
    G --> P[HasTagging]
    G --> Q[HasAuditing]
    G --> R[HasCaching]
    
    E --> S[String Transformers]
    E --> T[Numeric Transformers]
    E --> U[Custom Transformers]
    
    C --> V[Model Integration]
    C --> W[Collection Support]
    C --> X[Export Formats]
    
    style A fill:#e1f5fe
    style C fill:#c8e6c9
    style H fill:#fff3e0
    style G fill:#f3e5f5
    style E fill:#fce4ec
Loading

✨ Key Features

  • πŸš€ YAML-driven generation - Define DTOs in simple, readable YAML files
  • πŸ” Automatic validation - Built-in Laravel validation rules support
  • πŸ—οΈ Rich field types - 14+ field types including enums, UUIDs, nested DTOs, and JSON
  • πŸ”— Eloquent relationships - Full support for Laravel relationship types
  • ⚑ Direct property access - Clean, modern syntax with PHP 8.3+ features
  • πŸ“¦ Collection management - Convert models to DTO collections like Laravel Resources
  • 🎯 Powerful trait system - Built-in behavioral traits for common functionality (HasTimestamps, HasUuid, HasSoftDeletes, HasVersioning, HasTagging, HasAuditing, HasCaching) plus 3 functional traits (ValidatesData, ConvertsData, DtoUtilities) in every DTO
  • πŸ”„ Field transformers - Automatically transform field values during DTO creation with 10 built-in transformers (trim, lowercase, uppercase, title_case, slugify, abs, encrypt, normalize_phone, clamp_max, clamp_min)
  • πŸ“€ Multiple export formats - Export DTOs in 9 formats (JSON, YAML, CSV, XML, TOML, Markdown, PHP Array, Query String, MessagePack) with dedicated collection methods
  • πŸ› οΈ Powerful CLI commands - Generate, list, and manage DTOs from the command line
  • πŸ“ Smart path resolution - Automatic namespace-to-path conversion with custom organization
  • 🚨 Enhanced error handling - Detailed error messages with actionable suggestions
  • πŸ“¦ Zero configuration - Works out of the box with sensible defaults
  • πŸ§ͺ Fully tested - Comprehensive test suite with high coverage

πŸš€ Quick Start

Installation

composer require grazulex/laravel-arc

Basic Usage

1. Create a DTO definition

php artisan dto:definition-init UserDTO --model=App\\Models\\User --table=users

2. Define your DTO in YAML

# dto-definitions/UserDTO.yaml
header:
  dto: UserDTO
  namespace: App\DTO
  model: App\Models\User
  traits:
    - HasTimestamps
    - HasUuid

fields:
  name:
    type: string
    validation: [required, string, max:255]
    transformers: [trim, title_case]
  
  email:
    type: string
    validation: [required, email]
    transformers: [trim, lowercase]
  
  status:
    type: string
    default: "active"
    validation: [required, in:active,inactive]

3. Generate your DTO

php artisan dto:generate UserDTO.yaml

4. Use your DTO

// Convert a model to DTO
$user = User::find(1);
$userDto = UserDTO::fromModel($user);

// Convert a collection to DTO collection (like Laravel Resources)
$users = User::all();
$userDtos = UserDTO::collection($users); // Returns DtoCollection
// OR
$userDtos = UserDTO::fromModels($users); // Alternative syntax

// API Resource format
return response()->json($userDtos->toArrayResource());
// Output: {"data": [{"id": 1, "name": "John", "email": "[email protected]", "status": "active"}]}

// Export in multiple formats - 9 formats available
$json = $userDto->toJson();
$yaml = $userDto->toYaml();
$csv = $userDto->toCsv();
$xml = $userDto->toXml();
$toml = $userDto->toToml();
$markdown = $userDto->toMarkdownTable();
$phpArray = $userDto->toPhpArray();
$queryString = $userDto->toQueryString();
$messagepack = $userDto->toMessagePack();
$collection = $userDto->toCollection();

// Collection exports (with data wrapper like Laravel Resources)
$jsonData = UserDTO::collectionToJson($users);
$csvData = UserDTO::collectionToCsv($users);
$xmlData = UserDTO::collectionToXml($users);
$yamlData = UserDTO::collectionToYaml($users);
$markdownData = UserDTO::collectionToMarkdownTable($users);

// Validation
$userDto = UserDTO::fromArray($request->all());
if (!$userDto->isValid()) {
    return response()->json(['errors' => $userDto->getErrors()], 422);
}

🎯 Traits System

πŸ’‘ Laravel Arc provides a powerful trait system with two types of traits:

Functional Traits (Automatic)

Every DTO automatically includes these three powerful traits:

  • ValidatesData - Provides validation methods (validate(), passes(), fails())
  • ConvertsData - Provides conversion methods (toJson(), toCsv(), toXml(), etc.)
  • DtoUtilities - Provides utility methods (getProperties(), with(), equals())

Behavioral Traits (Optional) - 7 Available Traits

Add specific functionality by including traits in your YAML definition:

header:
  traits:
    - HasTimestamps    # Adds created_at, updated_at fields and methods
    - HasUuid         # Adds id field with UUID validation
    - HasSoftDeletes  # Adds deleted_at field for soft deletes
    - HasVersioning   # Adds version field and versioning methods
    - HasTagging      # Adds tags field and tagging methods
    - HasAuditing     # Adds audit trail fields and methods
    - HasCaching      # Adds caching capabilities

Example usage:

// Using functional traits (automatic)
$userDto = UserDTO::fromArray($data);
if (UserDTO::passes($data)) {
    $validated = UserDTO::validate($data);
}

// Using behavioral traits (if included)
$userDto = $userDto->addTag('premium')
                  ->nextVersion()
                  ->touch()
                  ->cache(3600);

πŸ”„ Field Transformers

Automatically transform field values during DTO creation:

fields:
  name:
    type: string
    transformers: [trim, title_case]  # "  john doe  " β†’ "John Doe"
  
  email:
    type: string
    transformers: [trim, lowercase]   # "  [email protected]  " β†’ "[email protected]"
  
  price:
    type: decimal
    transformers: [abs, clamp_min:0]  # -19.99 β†’ 19.99

Available transformers:

  • String transformers: trim, lowercase, uppercase, title_case, slugify
  • Numeric transformers: abs, clamp_max, clamp_min
  • Security transformers: encrypt
  • Phone transformers: normalize_phone (adds +33 prefix for French numbers starting with 0)

πŸ“– Documentation

Complete documentation and guides:

Core Concepts

Advanced Features

🎯 Use Cases

Laravel Arc is perfect for:

  • API Development - Type-safe request/response handling
  • Data Validation - Consistent validation across your application
  • Model Transformation - Clean data layer separation
  • Complex Forms - Nested form validation and processing
  • API Resources - Alternative to Laravel Resources with stronger typing

βš™οΈ Configuration

Laravel Arc works out of the box, but you can customize it:

// config/dto.php
return [
    'definitions_path' => base_path('database/dto_definitions'),
    'output_path' => base_path('app/DTO'),
];

πŸ“š Examples

Check out the examples directory for complete working examples:

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

πŸ“„ License

Laravel Arc is open-sourced software licensed under the MIT license.


Made with ❀️ for the Laravel community

About

🧬 Generate clean, typed DTO classes from YAML definitions in Laravel β€” fast, testable, and modular.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Contributors 3

  •  
  •  
  •