Zend_CodeGenerator

Introduction

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

Theory of Operation

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.

  1. // Passing configuration to the constructor:
  2. 'classes''name'    => 'World',
  3.             'methods''name' => 'hello',
  4.                     'body' => 'echo \'Hello world!\';',
  5.                 )),
  6.             ),
  7.         )),
  8.     )
  9. ));
  10.  
  11. // Configuring after instantiation
  12. 'hello')
  13.        ->setBody('echo \'Hello world!\';''World'// Render the generated file
  14. // or write it to a file:
  15. 'World.php'

Both of the above samples will render the same result:

  1. span style="color: #ff0000;">'Hello world!';
  2.     }
  3.  
  4. }

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_CodeGenerator makes this trivially simple, by leveraging Zend_Reflection.

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. span style="color: #ff0000;">'World''mrMcFeeley')
  2.        ->setBody('echo \'Hello, Mr. McFeeley!\';'// Render the generated file
  3. // Or, better yet, write it back to the original file:
  4. 'World.php'

The resulting class file will now look like this:

  1. span style="color: #ff0000;">'Hello world!''Hellow Mr. McFeeley!';
  2.     }
  3.  
  4. }

Zend_CodeGenerator