Download the PHP package cedriclombardot/twig-generator without Composer
On this page you can find all versions of the php package cedriclombardot/twig-generator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download cedriclombardot/twig-generator
More information about cedriclombardot/twig-generator
Files in cedriclombardot/twig-generator
Package twig-generator
Short Description A generator for PHP code based on Twig template engine
License MIT
Informations about the package twig-generator
TwigGenerator
TwigGenerator is a PHP code generator based on the Twig template engine. It leverages the power of Twig templates to simplify the generation of PHP code, to make it more extensible, and more readable.
Installation
Checkout this GitHub repository and setup the composer dependencies (Twig and Symfony ClassLoader):
Usage
To generate PHP classes, you need to create a "Builder", and one or more Twig templates. Then, add the new Builder to a "Generator", and generate the result.
Creating a Builder class
First, create a class extending TwigGenerator\Builder\BaseBuilder
- no need for methods at start.
Tip: Alternatively, a builder can implement the TwigGenerator\Builder\BuilderInterface
if it has to extend a custom class.
Creating Twig Templates
Next, create a couple twig templates under the templates/
directory. Usually, you need at least one template for the main structure, plus one template per feature added to the class.
Here is an example main template (or layout) for creating a custom PHP class (to be stored in templates/_base/common.php.twig
):
And now, an example for adding a custom method (to be stored in templates/MyBuilder.php.twig
):
Generating the code
Use a TwigGenerator\Builder\Generator
instance to generate the result. For instance:
The file will be generated in MyProject\Generated\MyBuilder.php
, as follows:
Other Examples
You can see some basic code generation samples in the tests, and on some GitHub repositories like fzaninotto/Doctrine2ActiveRecord, or cedriclombardot/AdmingeneratorGeneratorBundle.
Unit Tests
Then, just run:
phpunit