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] ...
e.g.

file "product.vo":

id:Id
price:Price
desc:Description

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 ./voGenerator.py -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;
$pVO->populate($row);
array_push($products, $pVO);
}

return $products;
}


Copy this code and paste it in your HTML
  1. #!/usr/bin/python
  2.  
  3. import re, sys, getopt, os
  4.  
  5. args = sys.argv
  6. ROOT_DIR = '/home/whatever'
  7. VO_DIR = ROOT_DIR + '/vo'
  8. VIEW_DIR = ROOT_DIR + '/views'
  9. dbAttr = []
  10. dbMap = {}
  11.  
  12. files = []
  13. finishedVOs = []
  14.  
  15. def usage():
  16. print "./voGenerator [-s single vo filename] [-a all views in vo dir] [-h show usage]"
  17.  
  18. def getAllViews():
  19. files = os.listdir(VO_DIR)
  20. filenames = []
  21. for f in files:
  22. filenames.append(os.path.splitext(f)[0])
  23. return filenames
  24.  
  25. try:
  26.  
  27. opts, args = getopt.getopt(sys.argv[1:], "has:", ["help", "update all", "vo="])
  28.  
  29. for o,a in opts:
  30. if o == "-a":
  31. files = getAllViews()
  32. elif o == "-s":
  33. files.append(a)
  34. print "Don't use single right now, it'll screw up the AllViews file"
  35. elif o in ("-h", "--help"):
  36. usage()
  37. sys.exit()
  38. else:
  39. assert(False, "Unhandled Option")
  40.  
  41. for fname in files:
  42. print "Updating %s" % (fname)
  43. #Parse .vo mapping
  44. for line in open( '%s/%s.vo' % (VO_DIR, fname)):
  45. entry = line.split(':')
  46. dbAttr.append(entry[0])
  47. dbMap[entry[0]] = entry[1].rstrip()
  48.  
  49. f = open('%s/%sVO.php' % (VIEW_DIR, fname.title()), 'w')
  50.  
  51. #php start tag
  52. f.write('<?php\n\n')
  53.  
  54. #class declaration
  55. f.write('\nclass %sVO {\n\n' % (fname.title()))
  56.  
  57. #private variables
  58. for attr in dbAttr:
  59. f.write('\tprivate $%s;\n' % (attr))
  60.  
  61. f.write('\n')
  62.  
  63. #getter functions
  64. for attr in dbAttr:
  65. f.write('\tpublic function get%s() { return $this->%s; }\n' % (dbMap[attr], attr))
  66. f.write('\n')
  67.  
  68. #setter functions
  69. for attr in dbAttr:
  70. f.write('\tpublic function set%s($val) { $this->%s = $val; }\n' % (dbMap[attr], attr))
  71. f.write('\n')
  72.  
  73. #dump out contents of the VO to stdout
  74. f.write('\tpublic function dump() {\n')
  75. for attr in dbAttr:
  76. f.write('\t\techo "%s: ".$this->get%s()."\\n";\n' % (dbMap[attr], dbMap[attr]))
  77. f.write('\t}\n')
  78. f.write('\n')
  79.  
  80. #populate function which takes a tuple from the db, and populates class
  81. f.write('\tpublic function populate($result_hash) {\n')
  82. for attr in dbAttr:
  83. f.write('\t\t$_%s = $result_hash["%s"];\n' % (attr, attr))
  84. for attr in dbAttr:
  85. f.write('\t\tif (isset($_%s)) $this->set%s($_%s);\n' % (attr, dbMap[attr], attr))
  86. f.write('\t}\n')
  87.  
  88. #end of class, closing php tag
  89. f.write('}\n\n?>\n')
  90.  
  91. f.close()
  92.  
  93. dbAttr = []
  94. dbMap = {}
  95. finishedVOs.append(fname.title()+'VO.php')
  96.  
  97. #Create the all-inclusive php include file
  98. f = open('%s/AllViews.php' % (VIEW_DIR), 'w')
  99. f.write('<?php\n')
  100. for voname in finishedVOs:
  101. f.write('require_once("%s");\n' % (voname))
  102. f.write('?>')
  103. f.close()
  104.  
  105.  
  106. except IOError:
  107. print 'file does not exist'
  108. except getopt.GetoptError, err:
  109. print str(err)
  110. usage()
  111. sys.exit(2)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.