O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #42. Generate Database Select Code

Use PHP to build code for database access directly from an XML description of the schema.

Building database access classes for SQL tables can require a lot of annoying, error-prone grunt work. In this hack, I use an XML file that describes a database schema and a code generator written in PHP to create the PHP classes automatically.

Tip

I used the same schema.xml file that I use in this hack, to generate the corresponding SQL [Hack #41] .

Figure 5-6 illustrates how the abstract schema XML is taken as input by the generator. The generator in turn creates the PHP classes in the mydb.php file.

Tip

This output file is temporary and you should never edit it directly.

The flow of the PHP SQL Select generator

Figure 5-6. The flow of the PHP SQL Select generator

The Code

schema.xml, representing the database, is shown in Example 5-27.

Example 5-27. XML representing a database schema

	<schema>
	  <table name="book">
		<field name="id" type="int" primary-key="true" />
		<field name="title" type="text" />
		<field name="publisher_id" type="int" />
		<field name="author_id" type="int" />
	  </table>
	  <table name="publisher">
		<field name="id" type="int" primary-key="true" />
		<field name="name" type="text" />
	  </table>
	  <table name="author">
		<field name="id" type="int" primary-key="true" />
		<field name="name" type="text" />
	  </table>
	</schema>

As when generating CRUD code [Hack #37] , you'll need a database wrapper; save ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required