This library provides some tools that you commonly need for generating PHP code.
Install via Composer:
{
"require": {
"gossi/php-code-generator": "dev-master"
}
}
There are two things you need to generate code.
- A generator
- CodeGenerator
- CodeFileGenerator
- A model to generate
- PhpClass
- PhpInterface
- PhpTrait
- PhpFunction
You can create these models and push all the data using a fluent API or read from existing code through reflection.
a) Simple:
use gossi\codegen\generator\CodeGenerator;
use gossi\codegen\model\PhpClass;
use gossi\codegen\model\PhpMethod;
use gossi\codegen\model\PhpParameter;
$class = new PhpClass();
$class->setName('my\cool\Tool');
->setMethod(PhpMethod::create('__construct')
->addParameter(PhpParameter::create('target')
->setType('string')
->setDescription('Creates my Tool')
)
);
$generator = new CodeGenerator();
$code = $generator->generate($class);
b) From Reflection:
use gossi\codegen\generator\CodeGenerator;
use gossi\codegen\model\PhpClass;
$class = PhpClass::fromReflection(new \ReflectionClass('MyClass'));
$generator = new CodeGenerator();
$code = $generator->generate($class);
The package ships with two generators, which are configurable with an associative array as constructor parameter. Alternatively if you have a project that uses the same configuration over and over again, extend the respective config object and pass it instead of the configuration array.
CodeGenerator
Creates code for a given model
Config: gossi\codegen\config\CodeGeneratorConfig
Options:
Key | Type | Default Value | Description |
---|---|---|---|
generateDocblock | boolean | true | enables docblock generation prior to code generation |
generateEmptyDocblock | boolean | true | when docblock generation is enabled, even empty docblocks will be generated |
CodeFileGenerator
Creates a complete php file with the given model inside.
Config: gossi\codegen\config\CodeFileGeneratorConfig
Options: Same options as CodeGenerator
plus:
Key | Type | Default Value | Description |
---|---|---|---|
headerComment | string | empty | A comment, that will be put after the <?php statement |
headerDocblock | string|Docblock | empty | A docblock that will be positioned after the possible header comment |
blankLineAtEnd | boolean | true | Places an empty line at the end of the generated file |
Feel free to fork and submit a pull request (don't forget the tests) and I am happy to merge.
- This project is a spin-off of the older schmittjoh/cg-library library.