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

Php Code Generator Laravel Package

murtukov/php-code-generator

PHPCodeGenerator generates PHP 7.4 source code via a fluent API. Build files with namespaces and imports, create classes/interfaces/traits/enums, methods/functions/closures, control structures, arrays, literals, comments, and configure global formatting options.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require murtukov/php-code-generator
    

    Requires PHP 7.4+.

  2. Basic Usage with Constructor Promotion Import the core class and generate code with constructor property promotion:

    use Murtukov\CodeGenerator\Generator;
    
    $generator = new Generator();
    $code = $generator->class('UserDTO')
        ->addProperty('name', 'string', '$name', true) // Enable constructor promotion
        ->addProperty('email', 'string', '$email', true)
        ->getCode();
    
  3. First Use Case: Scaffold a Model with Constructor Promotion Generate an Eloquent model with constructor property promotion:

    $generator = new Generator();
    $modelCode = $generator->class('Post')
        ->extends('App\Models\Model')
        ->addProperty('title', 'string', '$title', true) // Constructor promotion
        ->addProperty('content', 'string', '$content', true)
        ->addMethod('getRouteKeyName')
            ->addStatement('return $this->slug;')
        ->getCode();
    

Implementation Patterns

Common Workflows

1. Constructor Property Promotion for DTOs

Generate Data Transfer Objects (DTOs) with constructor promotion for cleaner initialization:

$generator = new Generator();
$dtoClass = $generator->class('UserDTO')
    ->addProperty('id', 'int', '$id', true)
    ->addProperty('name', 'string', '$name', true)
    ->addMethod('toArray')
        ->addStatement('return [')
        ->addStatement('    "id" => $this->id,')
        ->addStatement('    "name" => $this->name,')
        ->addStatement('];')
    ->getCode();

2. Integration with Laravel Artisan Commands

Scaffold models with constructor promotion via a custom Artisan command:

// app/Console/Commands/GenerateModel.php
use Murtukov\CodeGenerator\Generator;

class GenerateModel extends Command {
    protected $signature = 'generate:model {name}';
    public function handle() {
        $generator = new Generator();
        $code = $generator->class($this->argument('name'))
            ->extends('App\Models\Model')
            ->addProperty('title', 'string', '$title', true) // Constructor promotion
            ->addProperty('slug', 'string', '$slug', true)
            ->addProperty('created_at', 'datetime', 'new DateTime()')
            ->addProperty('updated_at', 'datetime', 'new DateTime()')
            ->getCode();
        file_put_contents("app/Models/{$this->argument('name')}.php", $code);
    }
}

3. Generating Tests with Constructor Promotion

Use constructor promotion in test stubs for concise initialization:

$testGenerator = new Generator();
$testClass = $testGenerator->class('UserTest')
    ->extends('Tests\TestCase')
    ->addMethod('testConstructorPromotion')
        ->addStatement('$user = new User(name: "John", email: "john@example.com");')
        ->addStatement('$this->assertEquals("John", $user->name);')
    ->getCode();

4. Dynamic Class Generation with Flexible Literals

Leverage the improved Literal component for dynamic property defaults:

$generator = new Generator();
$configClass = $generator->class('AppConfig')
    ->addProperty('debug', 'bool', 'env("APP_DEBUG") === "true"')
    ->addProperty('cache', 'array', '[]')
    ->addMethod('get')
        ->addStatement('return $this->{$key} ?? null;')
    ->getCode();

Integration Tips

Leverage Laravel’s Service Container

Bind the generator to the container for dependency injection:

// app/Providers/AppServiceProvider.php
public function register() {
    $this->app->singleton(Generator::class, function () {
        return new Generator();
    });
}

Use with Laravel Mix for TypeScript Interfaces

Generate TypeScript interfaces dynamically:

$tsGenerator = new Generator();
$interface = $tsGenerator->interface('UserInterface')
    ->addProperty('id', 'number')
    ->addProperty('name', 'string', '""')
    ->getCode();

Extend for Custom Syntax with Constructor Promotion

Override methods to add Laravel-specific syntax (e.g., $fillable + constructor promotion):

$generator->class('User')
    ->addFillable(['name', 'email'])
    ->addProperty('name', 'string', '$name', true) // Constructor promotion
    ->addProperty('email', 'string', '$email', true);

Gotchas and Tips

Pitfalls

  1. Constructor Promotion Syntax Quirks Ensure the third argument for addProperty is a valid literal (e.g., $name for promotion):

    // Correct
    $generator->addProperty('name', 'string', '$name', true);
    
    // Incorrect (will not promote)
    $generator->addProperty('name', 'string', 'null', true);
    
  2. Empty Block Rendering Changes The way empty blocks ({}) are rendered may differ across components. Test thoroughly:

    $generator->addMethod('emptyMethod')
        ->addStatement('{}'); // Verify rendering in generated code
    
  3. No Namespacing by Default Manually set the namespace or extend the generator:

    $generator->class('User')->setNamespace('App\Models');
    
  4. Limited PHP 8+ Support for New Features While constructor promotion is supported, avoid other PHP 8+ features (e.g., match, enum) unless explicitly patched.

  5. No Built-in File Writing The generator only outputs strings; handle file I/O separately:

    file_put_contents("app/Models/{$className}.php", $generator->getCode());
    

Debugging Tips

  1. Inspect Generated Code Use dd($generator->getCode()) to debug before writing to disk, especially for constructor promotion:

    $generator->addProperty('name', 'string', '$name', true);
    dd($generator->getCode());
    
  2. Check Method Chaining Ensure methods are chained correctly (e.g., ->addProperty()->addMethod()), and verify the true flag for constructor promotion:

    $generator->class('User')
        ->addProperty('name', 'string', '$name', true) // Constructor promotion
        ->addMethod('getName');
    
  3. Validate PHP Syntax Use php -l to lint generated files:

    php -l app/Models/GeneratedClass.php
    

Extension Points

  1. Custom Directives for Constructor Promotion Extend the generator to support Laravel-specific directives with constructor promotion:

    $generator->addDirective('fillable', ['name', 'email'])
        ->addProperty('name', 'string', '$name', true);
    
  2. Plugin System for Reusable Generators Create a trait for reusable generators with constructor promotion:

    trait EloquentGenerator {
        public function addTimestamps() {
            return $this->addProperties([
                'created_at' => ['datetime', 'new DateTime()'],
                'updated_at' => ['datetime', 'new DateTime()'],
            ]);
        }
    
        public function addConstructorPromotion($properties) {
            foreach ($properties as $name => $type) {
                $this->addProperty($name, $type, '$' . $name, true);
            }
            return $this;
        }
    }
    
  3. Integration with IDE Helpers Generate @property annotations for PHPStan/PSR-12, including constructor-promoted properties:

    $generator->addMethod('getName')
        ->addDocBlock('/** @return string */');
    
    $generator->addProperty('name', 'string', '$name', true)
        ->addDocBlock('/** @property string $name */');
    
  4. Dynamic Property Types with Literals Use mixed or array as fallbacks for dynamic properties, and leverage the improved Literal component:

    $generator->addProperty('metadata', 'array', '[]');
    $generator->addProperty('config', 'array', '$config', true); // Constructor promotion
    

Performance Notes

  • Cache Generated Code: Store generated files in bootstrap/cache/generated to avoid regeneration.
  • Avoid Over-Generation: Regenerate only what’s necessary (e.g., use timestamps for file checks).
  • Constructor Promotion Overhead: While minimal, generating classes with constructor promotion may add slight overhead. Cache aggressively if used frequently.

New in v0.1.6

  • Constructor Property Promotion: Added support for PHP 8 constructor property promotion, enabling cleaner class initialization.
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor