From 847be56c313cc9466b3a5198915643dad7db6304 Mon Sep 17 00:00:00 2001 From: Vallabh Kansagara Date: Wed, 14 Apr 2021 20:45:31 +0530 Subject: [PATCH] Adding example of trait generator Adding example for issue https://github.com/laminas/laminas-code/issues/24 --- docs/book/generator/examples.md | 43 +++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/docs/book/generator/examples.md b/docs/book/generator/examples.md index 3d3c1058..fb7d5e6b 100644 --- a/docs/book/generator/examples.md +++ b/docs/book/generator/examples.md @@ -370,3 +370,46 @@ $generator->addMethod( ); $code = $generator->generate(); ``` + + +## Generating Trait + +`Laminas\Code\Generator\FileGenerator` can be used to generate the contents of a *PHP* file. You can +include classes as well as arbitrary content body. + +```php +use Laminas\Code\Generator\FileGenerator; +use Laminas\Code\Generator\TraitGenerator; + +$traitclass = new TraitGenerator(); +$traitclass->addMethod('MethodOne'); +$traitclass->addConstant('VERSION','1.0.0'); + +$traitFile = new Laminas\Code\Generator\FileGenerator(); +$traitFile->setClass($traitclass); + +``` + +Calling `generate()` will generate the code -- but not write it to a file. You will need to capture +the contents and write them to a file yourself. As an example: + +```php +$code = $traitFile->generate(); +file_put_contents('Trait.php', $traitclass); +``` + +The above will generate the following file: + +```php +