Skip to content

northrook/php-generator

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.
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

About

PHP code generation.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Contributors

Languages