Wednesday, August 19, 2009

PHP class generator

Writing a PHP class file is a huge nightmare if it has 20 member variables or more. Why? Because you have to write set function and get function per each member variable. It's 40 functions. What if you have 30 member variables? hm...

PHP class generator is a solution for that kind of job. It takes the name of class and list of member variables as parameters, then generate PHP class source code automatically.

For example, if you want


class testClass
{
var $test1;
var $test2;

function __construct()
{
}
function setTest1($test1)
{
$this->test1 = $test1;
}
function getTest1()
{
return $this->test1;
}
function setTest2($test2)
{
$this->test2 = $test2;
}
function getTest2()
{
return $this->test2;
}
}
?>


For example, if you want just type

$php genClass.php testClass test1 test2 > testClass.php

then it generates source code you want. Stop writing get/set function manually from now. Here is source code. I hope you enjoy it.


/**
* File : genClass.php
*
* Generate PHP class file with given class name and list of member variables.
*
* @author : Brian @ Texas A&M University
*
* Usage : $php genClass.php className fieldName1 fieldName2 ... > filename
* Example : $php genClass.php testClass test1 test2 > testClass.php
* $cat testClass.php
class testClass
{
var $test1;
var $test2;

function __construct()
{
}
function setTest1($test1)
{
$this->test1 = $test1;
}
function getTest1()
{
return $this->test1;
}
function setTest2($test2)
{
$this->test2 = $test2;
}
function getTest2()
{
return $this->test2;
}
}
?>
*/

if ( $argc == 1 )
{
exit("Useage : genClass.php className fieldName1 fieldName2 ... > filename\n");
}

$name = $argv[1];
$max = $argc-1;

echo "echo "class $name\n";
echo "{\n";

for ( $i = 2 ; $i <= $max ; $i++ )
{
echo " var \$$argv[$i];\n";
}

echo "\n";
echo " function __construct()\n";
echo " {\n";
echo " }\n";
for ( $i = 2 ; $i <= $max ; $i++ )
{
$tmp = ucfirst($argv[$i]);
echo " function set$tmp(\$$argv[$i])\n";
echo " {\n";
echo " \$this->$argv[$i] = \$$argv[$i];\n";
echo " }\n";
echo " function get$tmp()\n";
echo " {\n";
echo " return \$this->$argv[$i];\n";
echo " }\n";

}
echo "}\n";

echo "?>\n";
?>