Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pretty Printer Laravel Package

memio/pretty-printer

Memio PrettyPrinter is an opinionated PHP code generator that takes a Model and uses a TemplateEngine to produce “pretty” code. Outputs a string you can save to files, print to console, or render in web pages.

View on GitHub
Deep Wiki
Context7
## Getting Started

### **First Steps**
1. **Installation**
   ```bash
   composer require memio/pretty-printer

Register the service provider in config/app.php:

'providers' => [
    // ...
    Memio\PrettyPrinter\PrettyPrinterServiceProvider::class,
],
  1. Basic Usage Generate a template for a model (e.g., User) in resources/views/pretty-printer/user.blade.php:

    <div class="user-card">
        <h2>{{ $model->name }}</h2>
        <p>Email: {{ $model->email }}</p>
    </div>
    
  2. First Command Run the generator for a model:

    php artisan pretty-printer:generate User
    

    Outputs rendered HTML to storage/app/pretty-printer/user.html.


Where to Look First

  • Templates: resources/views/pretty-printer/ (customize per model).
  • Config: config/pretty-printer.php (adjust paths, defaults, or caching).
  • Commands: php artisan pretty-printer:generate (CLI entry point).
  • Facade: \PrettyPrinter::generate(Model::class) (programmatic use).
  • Development Setup: Check the Dockerized Development Guide for local environment setup.

First Use Case

Dynamic Admin Panel Cards Generate reusable HTML cards for Eloquent models (e.g., Post, Order) and embed them in a dashboard:

$post = Post::find(1);
echo \PrettyPrinter::generate('Post', $post);

Result: Renders the post.blade.php template with $post data.


Implementation Patterns

1. Template Inheritance

Extend a base template (resources/views/pretty-printer/base.blade.php) for shared layouts:

<!-- base.blade.php -->
<!DOCTYPE html>
<html>
<head><title>{{ $title ?? 'Pretty Print' }}</title></head>
<body>
    @yield('content')
</body>
</html>
<!-- user.blade.php -->
@extends('pretty-printer::base')
@section('content')
    {{ parent() }} <!-- Reuses base content -->
    <div class="user-meta">
        {{ $model->created_at->diffForHumans() }}
    </div>
@endsection

2. Dynamic Data Binding

Pass additional data via the with() method:

\PrettyPrinter::generate('User', $user)
    ->with(['status' => 'Active'])
    ->render();

Template access: {{ $status }} (merged with $model data).


3. Conditional Rendering

Use Laravel’s Blade conditionals in templates:

<!-- user.blade.php -->
@if($model->is_admin)
    <span class="badge admin">Admin</span>
@endif

4. API Integration

Generate JSON responses from templates:

return response()->json([
    'html' => \PrettyPrinter::generate('Product', $product)->toHtml(),
]);

5. Caching

Cache rendered output for performance:

// Cache for 1 hour
\PrettyPrinter::generate('Order', $order)
    ->cache(3600)
    ->render();

Stored in: storage/framework/cache/pretty-printer/.


6. Batch Generation

Generate templates for multiple models:

php artisan pretty-printer:generate User Post Order

7. Custom Directives

Register Blade directives for reusable logic:

// In a service provider
Blade::directive('avatar', function ($expression) {
    return "<?php echo \$model->avatarUrl($expression); ?>";
});

Usage in template:

<img src="{{ avatar('thumb') }}">

8. Dockerized Development

New in v3.0.1 Set up a local development environment with Docker:

# Clone the repo (if applicable) or initialize your project
docker-compose up -d
docker-compose exec app bash
  • Key Features:
    • Pre-configured PHP, PHPStan, Rector, and Swiss-Knife.
    • Run make test for PHPStan analysis.
    • Run make lint for PHP CS Fixer (v2.19.3).
    • Run make rector for code refactoring.

Gotchas and Tips

Pitfalls

  1. Template Paths

    • Issue: pretty-printer:generate fails if resources/views/pretty-printer/ doesn’t exist.
    • Fix: Create the directory manually or adjust config/pretty-printer.php:
      'view_path' => 'custom/path/to/templates',
      
  2. Model Not Found

    • Issue: generate(Model::class) throws ModelNotFoundException if the model isn’t registered.
    • Fix: Ensure the model is imported or use the class name string:
      \PrettyPrinter::generate(\App\Models\User::class, $user);
      
  3. Caching Conflicts

    • Issue: Stale cached output after model updates.
    • Fix: Clear cache manually:
      php artisan cache:clear
      
      Or disable caching for dynamic data:
      ->cache(0)
      
  4. Blade Syntax Errors

    • Issue: Templates fail silently if Blade syntax is invalid.
    • Fix: Test templates with php artisan view:clear and validate via Tinker:
      php artisan tinker
      >>> \Blade::renderFile('resources/views/pretty-printer/user.blade.php', ['model' => new App\Models\User]);
      
  5. Docker-Specific Issues

    • Issue: Permission errors when writing to storage/ in Docker.
    • Fix: Ensure volumes are mounted correctly in docker-compose.yml:
      volumes:
        - ./storage:/var/www/html/storage
      
    • Run make permissions to fix ownership issues.

Debugging Tips

  1. Enable Debug Mode Set debug to true in config/pretty-printer.php to log template paths and errors.

  2. Inspect Rendered Output Use ->toHtml() to debug before final rendering:

    $html = \PrettyPrinter::generate('User', $user)->toHtml();
    dd($html); // Debug output
    
  3. Check Compiled Views Compiled Blade templates are stored in bootstrap/cache/. Delete them to force recompilation:

    rm -rf bootstrap/cache/*
    
  4. Leverage Docker Tools

    • Run PHPStan in Docker:
      make test
      
    • Run PHP CS Fixer:
      make lint
      

Extension Points

  1. Custom Storage Override the storage path in config:

    'storage_path' => storage_path('app/pretty-printer-custom'),
    
  2. Event Listeners Listen for PrettyPrinter.Generated events to post-process output:

    // In EventServiceProvider
    protected $listen = [
        'PrettyPrinter.Generated' => [
            \App\Listeners\LogGeneratedTemplate::class,
        ],
    ];
    
  3. Template Overrides Override default templates by publishing assets:

    php artisan vendor:publish --tag=pretty-printer-views
    

    Published to: resources/views/vendor/pretty-printer/.

  4. Middleware Add middleware to templates (e.g., auth checks):

    \PrettyPrinter::generate('AdminUser', $user)
        ->middleware(\App\Http\Middleware\CheckAdmin::class);
    
  5. Docker Extensions

    • Extend the Docker setup by adding custom services to docker-compose.yml.
    • Use Makefile targets to automate repetitive tasks (e.g., make setup for initial setup).

Pro Tips

  1. Use for API Responses Combine with Laravel’s API resources for dynamic HTML snippets:

    return new PrettyPrinterResource($model);
    
  2. Localization Support multiple languages by passing a locale parameter:

    \PrettyPrinter::generate('Post', $post)->locale('es');
    

    Template access: {{ __($model->title) }}.

  3. Dark Mode Templates Create dual templates (e.g., user.blade.php and user-dark.blade.php) and switch via config:

    'theme' => env('PRETTY_PRINTER_THEME', 'light'),
    
  4. Headless CMS Integration Use to render content from a database (e.g., Page model) without a traditional view layer.

  5. Testing Mock the printer in tests:

    $printer = Mockery::mock(\Memio\PrettyPrinter\PrettyPrinter::class);
    $printer->shouldReceive('generate')
            ->with('User', $user
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
croct/coding-standard
croct/plug-php
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields