Skip to content

Fragment Architecture

Jean-Marc Strauven edited this page Aug 4, 2025 · 1 revision

🧩 Fragment Architecture - TurboMaker V2.1.0 Revolution

⚡ 95% Performance Improvement with Pre-Compiled Fragments

TurboMaker V2.1.0 introduces a revolutionary Fragment Architecture powered by the Laravel ModelSchema package. This architectural shift delivers 95% performance improvements by moving from traditional template compilation to pre-compiled fragment injection.

🔍 What is Fragment Architecture?

Fragment Architecture is a pre-compilation system where the Laravel ModelSchema package generates insertable JSON/YAML fragments for each Laravel component. Instead of processing templates at generation time, TurboMaker V2.1.0 injects these optimized fragments directly into target files.

Traditional vs Fragment Approach

Traditional (V2.0) Fragment Architecture (V2.1.0)
⏱️ Template compilation at generation ⚡ Pre-compiled fragments
🐌 2-5 seconds generation time ⚡ 50-200ms generation time
🔄 Full template processing 🧩 Direct fragment injection
🏗️ Complex template engine 📦 Simple fragment insertion

🏗️ Architecture Components

Core Services from Laravel ModelSchema

// Schema parsing and validation
$schemaService = new SchemaService();

// Fragment generation coordination
$generationService = new GenerationService();

// Performance optimization
$optimizationService = new YamlOptimizationService();

13 Specialized Fragment Generators

  1. Model - Eloquent models with relationships and casts
  2. Migration - Database migrations with indexes and foreign keys
  3. Request - Form Request classes (Store/Update)
  4. Resource - API Resource classes for data transformation
  5. Factory - Model Factory for testing and seeding
  6. Seeder - Database Seeder for data population
  7. Controller - API and Web Controllers with CRUD operations
  8. Test - PHPUnit test classes (Feature and Unit)
  9. Policy - Authorization Policy classes
  10. Observer - Eloquent Observer with model event handlers (New in v2.0)
  11. Service - Business logic Service classes (New in v2.0)
  12. Action - Single-responsibility Action classes (New in v2.0)
  13. Rule - Custom Validation Rule classes (New in v2.0)

⚡ Performance Benchmarks

Generation Speed Comparison

# Traditional V2.0 Approach
Blog Post Module: 2.3s
E-commerce Product: 4.1s
User Management: 3.7s

# Fragment Architecture V2.1.0
Blog Post Module: 87ms   (96% faster)
E-commerce Product: 143ms (97% faster)
User Management: 125ms   (97% faster)

Memory Usage

# Traditional V2.0
Peak Memory: 45MB
Template Objects: 12MB
Processing Cache: 8MB

# Fragment Architecture V2.1.0
Peak Memory: 12MB (73% less)
Fragment Cache: 3MB
Processing Overhead: 1MB

🔧 Fragment Generation Workflow

1. Schema Processing

# User schema with V2.1.0 features
core:
  model: User
  table: users
  fields:
    name:
      type: string
      nullable: false
    email:
      type: email
      unique: true
    balance:
      type: money
      currency: EUR
      precision: 2
  relations:
    posts:
      type: hasMany
      model: App\Models\Post

2. Fragment Generation

// Generate all fragments
$fragments = $generationService->generateAll($schema);

// Result structure with JSON and YAML formats
$fragments = [
    'model' => [
        'json' => '{"model": {"class_name": "User", ...}}',
        'yaml' => 'model: {class_name: "User", ...}'
    ],
    'migration' => [
        'json' => '{"migration": {"table": "users", ...}}',
        'yaml' => 'migration: {table: "users", ...}'
    ],
    // ... all 13 component types
];

3. Fragment Injection

// TurboMaker V2.1.0 injects fragments into target files
$modelFragment = json_decode($fragments['model']['json'], true);
$turboMaker->injectModelFragment($modelFragment, 'app/Models/User.php');

$migrationFragment = json_decode($fragments['migration']['json'], true);
$turboMaker->injectMigrationFragment($migrationFragment, 'database/migrations/...');

🎯 Fragment Structure

Each fragment contains all the data needed for that component:

Model Fragment Example

{
  "model": {
    "class_name": "User",
    "table": "users",
    "namespace": "App\\Models",
    "fields": [
      {
        "name": "name",
        "type": "string",
        "nullable": false,
        "cast": "string"
      },
      {
        "name": "balance",
        "type": "decimal",
        "precision": 10,
        "scale": 2,
        "cast": "decimal:2"
      }
    ],
    "relations": [
      {
        "type": "hasMany",
        "name": "posts",
        "model": "App\\Models\\Post"
      }
    ],
    "traits": ["HasFactory", "SoftDeletes"],
    "options": {
      "timestamps": true,
      "soft_deletes": true
    }
  }
}

🔌 Advanced Features

Schema Optimization

// YAML optimization with intelligent caching
$optimizedSchema = $yamlOptimizationService->optimizeSchema($yamlContent);

// Schema analysis and recommendations
$analysis = $schemaOptimizationService->analyzeSchema($schema);
echo "Performance Score: {$analysis['performance_score']}/100";

Fragment Caching

// Fragment caching for repeated generation
$cacheKey = $generationService->getCacheKey($schema);
$fragments = $cache->remember($cacheKey, 3600, function() use ($schema) {
    return $generationService->generateAll($schema);
});

Streaming Generation

// Stream fragments for large schemas
$generationService->generateStreaming($largeSchema, function($componentType, $fragment) {
    echo "Generated {$componentType} fragment\n";
    $this->injectFragment($componentType, $fragment);
});

📊 Performance Analytics

Built-in Monitoring

// Performance tracking
$metrics = $generationService->getPerformanceMetrics();
echo "Average Generation Time: {$metrics['avg_time']}ms\n";
echo "Fragment Cache Hit Rate: {$metrics['cache_hit_rate']}%\n";
echo "Memory Peak Usage: {$metrics['peak_memory']}MB\n";

Real-time Analysis

# V2.1.0 provides real-time performance feedback
php artisan turbo:fragments User --analyze

Generating User fragments...
✅ Schema parsed: 12ms
✅ Fragments generated: 45ms
✅ Cache updated: 8ms
📊 Total time: 65ms (94% faster than traditional)

Fragment Sizes:
- Model: 2.1KB
- Migration: 1.8KB  
- Tests: 4.5KB
Total: 23.7KB

🛠️ Fragment Commands

Basic Fragment Generation

# Generate all fragments for a schema
php artisan turbo:fragments Post

# Generate specific fragment types
php artisan turbo:fragments User --only=model,migration,factory

# Generate with caching disabled
php artisan turbo:fragments Product --no-cache

Advanced Fragment Operations

# Analyze fragment performance
php artisan turbo:fragments Blog --analyze

# Export fragments to files
php artisan turbo:fragments User --export=storage/fragments/

# Import and inject fragments
php artisan turbo:inject storage/fragments/user/ app/

🔄 Migration from V2.0 to V2.1.0

Schema Compatibility

# V2.0 Schema (still supported)
model: User
fields:
  name: string
  email: string

# V2.1.0 Enhanced Schema  
core:
  model: User
  table: users
  fields:
    name:
      type: string
      nullable: false
    email:
      type: email
      unique: true

Performance Migration

# Check V2.0 performance baseline
php artisan turbo:benchmark --v2

# Migrate to V2.1.0 fragments
php artisan turbo:migrate-fragments

# Compare performance
php artisan turbo:benchmark --compare

🚀 Getting Started with Fragments

1. Install ModelSchema Dependency

composer require grazulex/laravel-modelschema

2. Create Your First Fragment Schema

# resources/schemas/post.yaml
core:
  model: Post
  table: posts
  fields:
    title:
      type: string
      rules: ['required', 'max:255']
    content:
      type: text
      rules: ['required']
    published_at:
      type: timestamp
      nullable: true

3. Generate with Fragment Architecture

php artisan turbo:fragments Post
# ⚡ Generated in 89ms (vs 2.1s traditional)

🎯 Best Practices

Fragment Optimization

  • Use schema caching for repeated generation
  • Enable fragment caching in production
  • Monitor performance metrics regularly
  • Analyze schema complexity before generation

Schema Design

  • Leverage V2.1.0 field types for better fragments
  • Use proper relationships for optimized generation
  • Include validation rules in schema definition
  • Design for fragment reusability

Fragment Architecture represents the future of Laravel code generation. Experience 95% faster generation with TurboMaker V2.1.0!

🏠 Home | 📖 Getting Started | 🏷️ Field Types | 📚 Commands

Clone this wiki locally