Weave 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

zetacomponents/php-generator

The Zeta Components PHP Generator provides an object-oriented API for programmatically generating PHP source code, including classes, methods, properties, parameters, constants, and docblocks. It is useful for scaffolding, automation, and dynamic code generation.

View on GitHub
Deep Wiki
Context7

Getting Started

Install it like any Composer package:

composer require zetacomponents/php-generator

The library is a small source-code emitter. You describe a class in PHP objects — name, parents, use statements, methods, parameters — and then ask it to produce the file. Nothing is generated automatically; it is a blank canvas with ergonomic accessors.

The classes are PSR-4 autoloaded under the package namespace (Zetacomponents\PhpGenerator\PhpGenerator, PhpGeneratorMethod, PhpGeneratorParameter, PhpGeneratorDependency, PhpGeneratorReturnType, PhpGeneratorException). Older documentation and blog posts use the eZ Components names (ezcPhpGenerator, ezcPhpGeneratorMethod, …); the API is the same. Confirm the exact prefix by looking in vendor/zetacomponents/php-generator/src.

Where to look first: PhpGenerator (the only orchestrator — properties like $className, $extends, $uses, and addMethod()/addDependency()/generate()/save()), then PhpGeneratorMethod for $body and $returnType. There is no maintained docs site; treat the source as the spec.

First use case — scaffold a value object:

use Zetacomponents\PhpGenerator\PhpGenerator;
use Zetacomponents\PhpGenerator\PhpGeneratorMethod;
use Zetacomponents\PhpGenerator\PhpGeneratorParameter;

$gen = new PhpGenerator( __DIR__ . '/Generated/Money.php' );
$gen->className = 'Money';

$ctor = new PhpGeneratorMethod( '__construct' );
$ctor->addParameter( new PhpGeneratorParameter( 'amount', 'int' ) );
$ctor->addParameter( new PhpGeneratorParameter( 'currency', 'string', "'EUR'" ) );
$ctor->body = '$this->amount = $amount;' . "\n" . '$this->currency = $currency;';
$gen->addMethod( $ctor );

echo $gen->generate();   // inspect the string
$gen->save();            // write the file

Implementation Patterns

  • Two-phase workflow: generate() then save(). generate() returns the code as a string and touches nothing; save() writes it. Keep generate() in tests and previews, and only call save() after a lint pass.
  • Method bodies are plain strings. All real logic lives in $method->body. Use nowdoc/heredoc plus sprintf() with placeholders to keep generated bodies readable; the package only handles signatures, visibility, docblocks, and braces.
  • Constructor injection via addDependency(). addDependency( new PhpGeneratorDependency( 'LoggerInterface', 'logger' ) ) emits a private typed property, a constructor parameter, and the $this->logger = $logger; assignment in one call — useful when generating service classes or factories.
  • Config-driven batch generation. This is the highest-leverage pattern: loop over a schema array (DB columns, an OpenAPI spec, a JSON fixture) and emit one class per entry. You get deterministic, diffable output instead of hand-copying boilerplate.
  • Wrap it in a command. Generate under app/Generated/, add that directory to your PSR-4 map, and expose an Artisan command (make:dtos, generate:api-client). Run the command in CI so the committed output can't drift.
  • Compose fluent interfaces. Set PhpGeneratorReturnType to $this or static on generated setters/builders, and use addUse( 'App\\Contracts\\Foo' ) so fully-qualified names stay out of method bodies.
  • Constants and properties. addConstant(), addVariable(), and addUse() cover most of the class-level surface; use them to emit enums, typed properties, and imports without string concatenation.

Gotchas and Tips

  • It is a dormant package (4 stars, 0 listed dependents, archived upstream). Pin an exact version and treat upgrades as manual merges. For new code, compare against nette/php-generator, which is actively maintained and has a richer AST-like API — the migration cost is small because the concepts map almost 1:1.
  • License metadata reads NOASSERTION. The code is Apache-2.0 (Zeta Components heritage), but verify the LICENSE file before shipping inside a commercial product.
  • save() silently overwrites the target path. Write to a temp file and rename() if you need atomicity, and ensure the directory exists and is writable — otherwise you get a PhpGeneratorException.
  • No validation of body. Broken PHP is emitted happily. Run php -l (or a PHP-Lint library) on every generated file in CI.
  • Escaping bites at the boundaries. Backslashes in FQCNs inside strings need doubling, and use nowdoc — not heredoc — when the body contains $ that you do not want interpolated.
  • Defaults are literal strings. new PhpGeneratorParameter( 'currency', 'string', "'EUR'" ) needs the quotes baked in; pass integers as '0'. Passing null omits the default entirely.
  • Namespace support depends on the version. Early releases predate PHP namespaces, so older code expects the namespace to be folded into className. Check the constructor/properties of the installed version before relying on it.
  • No extension hooks. To customize formatting, either subclass PhpGenerator and override generate(), or post-process the returned string. Do not expect visitors or a template engine.
  • Debugging is trivial — lean into it. Always var_dump( $gen->generate() ) before save(); because the output is plain text you can diff it against a fixture and eyeball whitespace regressions.
  • Transitive dependency on zetacomponents/base. If you see ezcBase* autoload errors, Composer did not pull the base package (or your autoloader was hand-rolled). Let Composer resolve it rather than requiring classes individually.
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.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource