Skip to content

Repository files navigation

php-generator

PHP code generation.

Overview

This package builds PHP source code fluently. Two entry points exist:

  • PhpGenerator — file shell (<?php, namespace, use imports, 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()) calls generate() first, then wraps the result in a generated-file banner (name, timestamp, generator class, content hash) and normalizes leading tabs to spaces.
useNorthrook\Core\PhpClass;
$class = newPhpClass('App\\Service', strict: true);
$class->addProperty('name', 'string');
$bare = $class->generate(); // no banner$forFile = (string) $class; // banner + normalized indentation

Example

useNorthrook\Core\PhpClass;
useNorthrook\Core\PhpGenerator\Visibility;
$class = newPhpClass('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

About

PHP code generation.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages