Simple PHP ViewObject generator

/ Published in: PHP
Save to your folder(s)

Any time I make PHP applications that interact with a database, I use this script. It generates one or more self-populating "View Objects" (a class that represents a single record from a DB). For example, rather than access a MySQL record-set by array indices (e.g. $row[1]), you can populate an object with the record's values, and reference them like properties in an object (e.g. $productVO->price).

To use:
1. Create a ".vo" file. For example, if you have a Products table, make "products.vo".
2. In this file, you will map column names to some string of your choice. This string will be used to name the getter/setter functions in the generated class. "get" and "set" will be pre-pended to these mapped names automatically, so don't include them. Like so:
[column 1 name]:[desired function name]
[column 2 name]:[desired function name] ...

file "product.vo":


This will generate a class with functions "getId()", "getPrice()", and "getDescription()", returning the appropriate attribute.
3. Edit the folder names in the python source below to match your setup
4. Run ./ -a

This will generate views for all ".vo" files in the directory specified in the python script as well as an "AllViews.php" file which, when included in your PHP code, imports all view files. View files take the form [filename]VO.php as in ProductVO.php

To populate these objects, use the following snippit:

function getAllProducts() {
$products = array();
$row = array();
$result = query("SELECT * FROM products");

while ($row = mysql_fetch_assoc($result)) {
$pVO = new ProductsVO;
array_push($products, $pVO);

return $products;

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.