Zend\Code\Generator

Zend\Code\Generator provides facilities to generate arbitrary code using an object-oriented interface, both to
create new code as well as to update existing code. While the current implementation is limited to generating PHP
code, you can easily extend the base class in order to provide code generation for other tasks: JavaScript,
configuration files, apache vhosts, etc.

In the most typical use case, you will simply instantiate a code generator class and either pass it the appropriate
configuration or configure it after instantiation. To generate the code, you will simply echo the object or call
its generate() method.

// Passing configuration to the constructor:$file=newZend\Code\Generator\FileGenerator(array('classes'=>array(newZend\Code\Generator\ClassGenerator(array('name'=>'World','methods'=>array(newZend\Code\Generator\MethodGenerator(array('name'=>'hello','body'=>'echo \'Hello world!\';',)),),)),)));// Configuring after instantiation$method=newZend\Code\Generator\MethodGenerator();$method->setName('hello')->setBody('echo \'Hello world!\';');$class=newZend\Code\Generator\ClassGenerator();$class->setName('World')->setMethod($method);$file=newZend\Code\Generator\FileGenerator();$file->setClass($class);// Render the generated fileecho$file;// or write it to a file:file_put_contents('World.php',$file->generate());

Both of the above samples will render the same result:

1
2
3
4
5
6
7
8
9
10
11

<?phpclassWorld{publicfunctionhello(){echo'Hello world!';}}

Another common use case is to update existing code – for instance, to add a method to a class. In such a case, you
must first inspect the existing code using reflection, and then add your new method. Zend\Code\Generator makes
this trivially simple, by leveraging ZendCodeReflection.

As an example, let’s say we’ve saved the above to the file World.php, and have already included it. We could
then do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

$class=Zend\Code\Generator\ClassGenerator::fromReflection(newZend\Code\Reflection\ClassReflection('World'));$method=newZend\Code\Generator\MethodGenerator();$method->setName('mrMcFeeley')->setBody('echo \'Hello, Mr. McFeeley!\';');$class->setMethod($method);$file=newZend\Code\Generator\FileGenerator();$file->setClass($class);// Render the generated fileecho$file;// Or, better yet, write it back to the original file:file_put_contents('World.php',$file->generate());