1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.codegenerator.introduction">
4 <title>Introduction</title>
7 <classname>Zend_CodeGenerator</classname> provides facilities to generate
8 arbitrary code using an object oriented interface, both to create new
9 code as well as to update existing code. While the current
10 implementation is limited to generating <acronym>PHP</acronym> code, you can easily extend
11 the base class in order to provide code generation for other tasks:
12 JavaScript, configuration files, apache vhosts, etc.
15 <sect2 id="zend.codegenerator.introduction.theory">
16 <title>Theory of Operation</title>
19 In the most typical use case, you will simply instantiate a code
20 generator class and either pass it the appropriate configuration or
21 configure it after instantiation. To generate the code, you will
22 simply echo the object or call its <methodname>generate()</methodname> method.
25 <programlisting language="php"><![CDATA[
26 // Passing configuration to the constructor:
27 $file = new Zend_CodeGenerator_Php_File(array(
29 new Zend_CodeGenerator_Php_Class(array(
32 new Zend_CodeGenerator_Php_Method(array(
34 'body' => 'echo \'Hello world!\';',
41 // Configuring after instantiation
42 $method = new Zend_CodeGenerator_Php_Method();
43 $method->setName('hello')
44 ->setBody('echo \'Hello world!\';');
46 $class = new Zend_CodeGenerator_Php_Class();
47 $class->setName('World')
50 $file = new Zend_CodeGenerator_Php_File();
51 $file->setClass($class);
53 // Render the generated file
56 // or write it to a file:
57 file_put_contents('World.php', $file->generate());
61 Both of the above samples will render the same result:
64 <programlisting language="php"><![CDATA[
70 public function hello()
79 Another common use case is to update existing code -- for instance,
80 to add a method to a class. In such a case, you must first inspect
81 the existing code using reflection, and then add your new method.
82 <classname>Zend_CodeGenerator</classname> makes this trivially simple, by
83 leveraging <link linkend="zend.reflection">Zend_Reflection</link>.
87 As an example, let's say we've saved the above to the file
88 "<filename>World.php</filename>", and have already included it. We could then do the
92 <programlisting language="php"><![CDATA[
93 $class = Zend_CodeGenerator_Php_Class::fromReflection(
94 new Zend_Reflection_Class('World')
97 $method = new Zend_CodeGenerator_Php_Method();
98 $method->setName('mrMcFeeley')
99 ->setBody('echo \'Hello, Mr. McFeeley!\';');
100 $class->setMethod($method);
102 $file = new Zend_CodeGenerator_Php_File();
103 $file->setClass($class);
105 // Render the generated file
108 // Or, better yet, write it back to the original file:
109 file_put_contents('World.php', $file->generate());
113 The resulting class file will now look like this:
116 <programlisting language="php"><![CDATA[
122 public function hello()
127 public function mrMcFeeley()
129 echo 'Hellow Mr. McFeeley!';