northrook / php-generator
PHP code generation.
dev-main
2026-06-26 17:57 UTC
Requires
- php: >=8.4
- northrook/core-contracts: dev-main
- symfony/var-exporter: ^8.1
Requires (Dev)
- northrook/php-cs: dev-main
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^12.2
This package is auto-updated.
Last update: 2026-06-26 17:57:43 UTC
README
PHP code generation.
Overview
This package builds PHP source code fluently. Two entry points exist:
PhpGenerator— file shell (<?php, namespace,useimports, optional raw body)PhpClass— extends that to emit classes with constants, properties, methods, and traits
generate() vs casting to string
These produce different output:
generate()returns bare PHP source suitable for inspection or further processing.(string) $generator(or__toString()) callsgenerate()first, then wraps the result in a generated-file banner (name, timestamp, generator class, content hash) and normalizes leading tabs to spaces.
use Northrook\Core\PhpClass; $class = new PhpClass('App\\Service', strict: true); $class->addProperty('name', 'string'); $bare = $class->generate(); // no banner $forFile = (string) $class; // banner + normalized indentation
Example
use Northrook\Core\PhpClass; use Northrook\Core\PhpGenerator\Visibility; $class = new PhpClass('App\\UserRepository', strict: true); $class ->comment('Repository for User entities.') ->implements('App\\Contracts\\UserRepositoryInterface') ->addConstant('TABLE', 'users') ->addProperty('connection', 'PDO', comment: 'Database connection.') ->addMethod( 'find', 'return $this->connection->query(...);', arguments: 'int $id', returns: '?User', visibility: Visibility::PUBLIC, ); file_put_contents('UserRepository.php', (string) $class);
Development
vendor/bin/phpstan analyse vendor/bin/phpunit dprint fmt