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 Generator Laravel Package

nette/php-generator

Generate PHP code via a fluent API: build classes, interfaces, functions, methods, properties, namespaces, and PHPDoc, then render to valid PHP. Handy for code generators, scaffolding tools, and runtime code output with strict formatting and escaping.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing via Composer: composer require nette/php-generator. The package requires PHP 8.1+ and integrates with PHP-Parser 5+. Begin with the core types: PhpFile, PhpNamespace, and ClassType. A minimal first use is generating a simple class:

use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\PhpFile;
use Nette\PhpGenerator\PhpNamespace;

$namespace = new PhpNamespace('App\Entity');
$namespace->add(new ClassType('User')
    ->addProperty('id', 0)
    ->addMethod('getId')
        ->setPublic()
        ->setReturnType('int')
        ->setBody('return $this->id;'));

$file = (new PhpFile)
    ->add($namespace);

echo $file;
// Outputs clean PHP code with proper formatting and use statements

Check the README and examples in the repo first—especially examples/generate.php.

Implementation Patterns

  • Code Generation Workflows: Use Factory::fromClassReflection() to reverse-engineer existing classes (e.g., for scaffolding or migration tools). Combine with ClassManipulator to programmatically add methods/properties to existing types before generation.
  • Unified add() API: Leverage PhpFile::add() to handle all top-level constructs (classes, enums, traits, functions, namespaces) in one call. It auto-assigns namespaces and manages file structure, eliminating boilerplate:
    $file = new PhpFile;
    $file->add('App\Services\OrderService');
    $file->add(new GlobalFunction('formatCurrency'));
    
  • Dynamic Class Building: Use ClassType::fromCode() to parse existing PHP snippets into AST-like structures, then mutate them before regeneration. Useful for patching generated code (e.g., adding attributes orDocBlocks).
  • Printer Customization: Inject custom PsrPrinter subclasses via Printer::setDumper() for project-specific formatting (e.g., enforcing PSR-12 or internal style). Override printAttribute() to support custom attributes.
  • Integration with Symfony/Doctrine: Generate entity classes or DTOs from schema metadata by combining Factory::fromClassReflection() with ClassManipulator—ideal for custom bundles or ORM extensions.

Gotchas and Tips

  • FQN Handling: Since v4.2.0, ClassLike constructors accept FQNs (e.g., 'App\Model\User') and auto-extract namespaces—but the legacy $namespace constructor parameter is deprecated. Prefer setNamespace() to avoid surprises.
  • Namespace Assignment Side Effects: PhpNamespace::add() now always assigns itself to added ClassLike objects (getNamespace() is never null). Check logic relying on null checks before upgrading.
  • Validation Overlaps: The package enforces strict validation (e.g., duplicate class/method names throw exceptions). Use hasTrait(), hasConstant(), getMethod() early to avoid runtime errors in dynamic codegen.
  • Attribute Edge Cases: Falsy attributes (e.g., @var false) may not print without explicit handling. Always verify with Printer::printAttributes() in tests.
  • Extensibility Points: Extend Dumper for custom literal formatting, or override Printer methods like printDocComment() for strict docblock compliance. Note: v4+ requires PHP 8.1+ enums for Visibility, PropertyAccessMode, etc.
  • Debugging: Use Dumper::dump() or Printer::dump() on any node (e.g., Method, Parameter) for runtime inspection of its structure before printing.
  • PHP 8.5+ Gotchas: Property hooks and asymmetric visibility require v4.1.7+. When extracting classes with hooks, ensure $withBodies = false for interfaces (v4.1.8+ rejects body extraction there).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport