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 #37. Generate CRUD Database Code

Automatically generate the code to create, read, update, and delete (CRUD) records from your database tables.

This book presents several hacks that will help you speed up your database development by generating the required PHP and SQL code. In this hack, I show you how to build a generator that will create PHP 4 (or 5) classes that wrap database records. With these classes, you will be able to create, read, update, and delete individual records on any table, without spending lots of time writing the database code yourself.

Figure 5-4 shows the flow from the schema file into the generator, which in turn creates the output PHP code. I've rendered the output code as dashes because it's temporary and should never be altered manually.

The flow through the generator

Figure 5-4. The flow through the generator

The Code

Save the XML representing a database schema (shown in Example 5-14) as schema.xml.

Example 5-14. An XML document that maps to the 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> ...

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