lang="en-US"> FREE PHP Tool: Class File Generator –  Design1online.com, LLC

FREE PHP Tool: Class File Generator

Want to quickly generate a class file for a table in your database? This script takes your connection information, the name of the table, the name of your class and gives you a formatted class file you can download and use in a snap. Features include the ability to add get/set methods for each field, a simple debugger, and a print object function. It’s available under the GNU public license.

Download the Class File Generator

The Source Code

<?php
/*********
* File: index.php
* Date: 4.5.2012
* Author: design1online.com, LLC
* Purpose: generate a oop class file for a mysql database table
*********/
DEFINE("AUTHOR", "Design1online.com, LLC");

if ($_POST['generate'])
{
    $fields = array();
    $keys = array();

    if (!$_POST['host'])
        $_POST['host'] = "localhost";

    //connect to the database
    mysql_connect ($_POST['host'], $_POST['username'], $_POST['pass'])
        or die ('Cannot connect to the database: ' . mysql_error());

    mysql_select_db ($_POST['db'])
        or die ('Cannot select database: ' . mysql_error()); 

    $table = mysql_query("SHOW columns FROM {$_POST['table']}")
        or die ('Cannot load table: ' . mysql_error());

    //load the table fields and keys
    while ($schema = mysql_fetch_assoc($table))
    {

        $field = array(
            "name" => $schema['Field'],
            "type" => $schema['Type']
        );

        if ($schema['Key'])
            array_push($keys, $field);

        array_push($fields, $field);
    }

    $filename = ($_POST['name']) ? $_POST['name'] : $_POST['table'];

    //build the file
    $file = "/**********
* File: $filename.class.php
* Author: " . AUTHOR . "
* Created: " . date('n.j.Y g:ia') . "
* Free PHP Class Generator: http://design1online.com/phpclassfilegenerator
**********/

class $filename";

    if ($_POST['extends'])
        $file .= " extends {$_POST['extends']}";

    $file .= " {nn";

    if ($_POST['vars'])
    {
        foreach ($fields as $index => $field)
            $file .= "tvar $" . $field['name'] . ";n";
    }

    if ($_POST['debug'])
        $file .= "tvar $debugger = false;n";

    $file .= "nt/*********
t* Purpose: Default constructor
t* Preconditions: None
t* Postconditions: None
t*********/
tfunction $filename(";

    foreach ($keys as $index => $field)
        $keynames[] = $field['name'];

    //build the constructor parameters
    if ($_POST['constructor'])
        $file .= "$" . implode(", $", $keynames);

    $file .= ") {n";

    if ($_POST['debug'])
        $file .= "nttif ($this->debugger)ntttecho "DEBUGGER: initializing $filename object";n";

    //build the constructor
    if ($_POST['constructor'])
    {
        foreach ($keys as $index => $field)
        {
            $file .= "nttif (!$" . $field['name'];

            if (strpos($field['type'], "int") !== false || strpos($field['type'], "decimal") !== false
                || strpos($field['type'], "float") !== false || strpos($field['type'], "double") !== false
                || strpos($field['type'], "real") !== false || strpos($field['type'], "bit") !== false
                || strpos($field['type'], "bit") !== false || strpos($field['type'], "bool") !== false
                || strpos($field['type'], "serial") !== false)
                    $file .= " || !is_numeric($" . $field['name'] . ")";

            $file .= ")ntttreturn;n";
        }

        $file .= "ntt$result = mysql_query("SELECT * FROM {$_POST['table']} WHERE ";

        $append = false;

        foreach ($keys as $index => $field)
        {    
            if ($append)
                $file .= " AND ";

            $file .= "{$field['name']} = '$" . $field['name'] . "'";

            if (!$append)
                $append = true;
        }

        $file .= "")ntttor die('Cannot init constructor in $filename.class.php: ' . mysql_error());nntt$row = mysql_fetch_assoc($result);n";

        foreach ($fields as $index => $value)
        {
            $file .= "ntt$this->{$value['name']} = ";

            if (strpos($value['type'], "varchar") !== false || strpos($value['type'], "text") !== false
                || strpos($value['type'], "blob") !== false || strpos($value['type'], "enum") !== false
                || strpos($value['type'], "set") !== false || strpos($value['type'], "binary") !== false)
                    $file .= "stripslashes(html_entity_decode(";

            $file .= "$row['{$value['name']}']";

            if (strpos($value['type'], "varchar") !== false || strpos($value['type'], "text") !== false
                || strpos($value['type'], "blob") !== false || strpos($value['type'], "enum") !== false
                || strpos($value['type'], "set") !== false || strpos($value['type'], "binary") !== false)
                    $file .= ", ENT_QUOTES))";

            $file .= ";";
        }
    }

    $file .= "nnt} //end default constructor";

    //check to see if they want the print function
    if ($_POST['print'])
    {
        $file .= "nnt/*********
t* Purpose: Display the object
t* Preconditions: None
t* Postconditions: None
t*********/
tfunction print() {";

        if ($_POST['debug'])
            $file .= "nnttif ($this->debugger)ntttecho "DEBUGGER: printing $filename object";";

        $file .= "nnttecho "<b>Displaying $filename Object</b><br/><br/>";

        foreach ($fields as $index => $value)
            $file .= "nttt{$value['name']} = $this->{$value['name']}<br/>";

        $file .= "";nnt} //end print function";
    }

    //check to see if they want the get methods
    if ($_POST['get'])
    {
        foreach ($fields as $index => $value)
        {
            $file .= "nnt/*********
t* Purpose: Get the value from the {$value['name']} field
t* Preconditions: None
t* Postconditions: {$value['name']} field value returned
t*********/
tfunction get" . ucFirst($value['name']) . "() {";

            if ($_POST['debug'])
                $file .= "nnttif ($this->debugger)ntttecho "DEBUGGER: calling {$filename}->get" . ucFirst($value['name']) . " method";n";

            $file .= "nttreturn $this->{$value['name']};nt}";

        }
    }

    //check to see if they want the set methods
    if ($_POST['set'])
    {
        foreach ($fields as $index => $value)
        {
            $file .= "nnt/*********
t* Purpose: Set the value of the {$value['name']} field
t* Preconditions: None
t* Postconditions: object and table data set to $value
t*********/
tfunction set" . ucFirst($value['name']) . "($value) {";

            if ($_POST['debug'])
                $file .= "nnttif ($this->debugger)ntttecho "DEBUGGER: calling {$filename}->get" . ucFirst($value['name']) . " method";";

            $file .= "nnttif (!$value)ntttreturn "Invalid value";

ttmysql_query("UPDATE {$_POST['table']} SET {$value['name']}='$value' WHERE ";

            $append = false;

            foreach ($keys as $index => $field)
            {    
                if ($append)
                    $file .= " AND ";

                $file .= "{$field['name']} = '$this->" . $field['name'] . "'";

                if (!$append)
                    $append = true;
            }

            $file .= "")ntttor die('Cannot set value for {$value['name']}: ' . mysql_error());nntt$this->{$value['name']} = $value;nt}";

        }
    }

    $file .= "nn} //end $filename.class.php";

    //setup the headers so you can download the file
    header('Content-type: text');
    header("Content-Disposition: attachment; filename=$filename.class.php");
    echo $file;
}

if (!$_POST['generate'])
{
    echo "
    <center>
    <h1>Class File Generator</h1>
    <form action="#" method="post">
        <table cellpadding="2" cellspacing="2" width="80%">
            <tr>
                <th>MySQL Connection</th>
                <th>Class Options</th>
            </tr>
            <tr>
                <td width="50%" valign="top">
                    <p>Host: <input type="text" name="host" value="{$_POST['host']}" /></p>
                    <p>Username: <input type="text" name="username" value="{$_POST['username']}" /></p>
                    <p>Password: <input type="password" name="pass" value="{$_POST['pass']}" /></p>
                    <p>Database: <input type="text" name="db" value="{$_POST['db']}" /></p>
                    <p>Table: <input type="text" name="table" value="{$_POST['table']}" /></p>
                    <p align="center">
                        <input type="submit" name="generate" value="Generate Class" />
                    </p>
                </td>
                <td>
                    <p>
                        Class Name: <input type="text" name="name" value="{$_POST['name']}" />
                        <br/><i>tablename used by default</i>
                    </p>
                    <p>
                        Extends Class: <input type="text" name="extends" value="{$_POST['extends']}" />
                        <i>(optional)</i>
                    </p>
                    <blockquote>
                        <p><input type="checkbox" name="vars" checked="checked" />Include variable declarations</p>
                        <p><input type="checkbox" name="constructor" checked="checked" />Include default constructor</p>
                        <p><input type="checkbox" name="get" />Include get functions for all fields</p>
                        <p><input type="checkbox" name="set" />Include set functions for all fields</p>
                        <p><input type="checkbox" name="print" />Include print function</p>
                        <p><input type="checkbox" name="debug" />Include debugger</p>
                    </blockquote>
                </td>
            </tr>
        </table>
        <p>
            <a href="http://design1online.com/downloads/classfilegenerator.zip">Download Source Code</a><br/>
                <b>GNU Public License</b>
        </p>
        <p>
            <a href="http://design1online.com">by design1online.com, LLC</a>
        </p>
    </form>
    </center>";

You may also like...

Leave a Reply