Automatically generate a PHP class based on the table structure

Source: Internet
Author: User
Tags zend framework
Automatically generate a PHP class based on the table structure

The Zend framework provides a way for class and table mapping to create a class that inherits Zend_db_table. When querying, Zend automatically processes table fields, generates an object, and object properties are created dynamically, so it is public. There are two big questions, one is that the property of class is public, and the second is that class property is only determined after the code executes. As a result, I wrote a program to generate the corresponding class according to the table information.

?

?

 Database = $config [' database ']; $conn = Isset ($config [' Password '])? mysql_connect ($config [' Host '], $config [' User '], $config [' Password ']): mysql_connect ($config [' Host '], $config ['    User ']);    if (! isset ($conn)) {die (' Failed to connect. '. Mysql_error ());    } $this->giventables = $config [' Tables '];    if (Isset ($this->giventables) && (!is_array ($this->giventables) | | empty ($this->giventables)) {    Die (the "Tables ($this->giventables) in config are not a array or it is empty.");        } $this->parentclass = $config [' ParentClass '];    if ($config [' excludedproperties ']) {$this->excludedproperties = $config [' excludedproperties '];  if (!is_array ($this->excludedproperties) | | empty ($this->excludedproperties)) {die (' excludedproperties should    Be a array and shoudnot be empty. ');    }} if ("File_exists (self::D efault_dir)") {mkdir (self::D efault_dir); }} Public Function __destroy () {       Mysql_close (); Public Function generateclasses () {$allTables = $this->gettables (); Var_dump ($allTables); $tables = $this->given Tables?    $this->giventables: $allTables;    if (empty ($tables)) {die ("empty given tables");    } foreach ($tables as $table) {$index = Array_search ($table, $allTables);    if (!is_int ($index)) {echo "Table ($table) not found in database ({$this->database}). \ n";    Continue    } $this->generateclassfortable ($table);        }} Private Function Generateclassfortable ($table) {$class = Ucfirst ($this->transform ($table)); $fileName = self::D efault_dir.        "/$class. php"; if (file_exists ($fileName)) {echo "the file ($fileName) already exists.        You need delete if first.\n ";        Return        } $columns = $this->gettablecolumns ($table);        if (!isset ($columns) | | empty ($columns)) {echo "the table ($table) doesn ' t has columns.\n";          Return     }           $this->file = fopen ($fileName, ' w ');        if (! isset ($this->file)) {die ("Failed to open File: $fileName");        } echo "Generating class for table: $table. \ n"; $this->writetofile ("
 ParentClass) {$this->writetofile ("class $class extends {$this->parentclass} {");        } else {$this->writetofile ("class $class {");        } $this->generateconst ($table);        $this->generatecolumnpropmapping ($columns);        $this->generatevalidateconfig ($table, $columns);        $this->generateproperties ($columns);        $this->generategetters ($columns);        $this->generatesetters ($columns);        $this->writetofile ("}");        $this->writetofile ("?>");        Fclose ($this->file);    echo "Class ($class) was created in the file ($fileName). \ n"; } Private Function Generatecolumnpropmapping ($columns) {$this->writetofile (' private static $_colpropmapping = array (', 1); foreach ($columns as $key = = $value) {$prop = $this->transform ($key); $this->writetofile ("' $key ' = ' $p Rop ', ", 2);}    $this->writetofile ('); ', 1); $this->writenewline ();    } Private Function Generateconst ($table) {$this->writetofile ("Const TABLE_NAME = ' $table ';", 1);    $this->writenewline (); The Private Function generategetters ($columns) {foreach ($columns as $key = = $value) {$prop = $thi        S->transform ($key);            if ($this->shouldexcludeprop ($prop)) {continue; } $method = ' get '.            Ucfirst ($prop);            $this->writetofile ("Public function $method () {", 1); $this->writetofile (' return $ ').            "This-> $prop;", 2);            $this->writetofile ("}", 1);        $this->writenewline ();        }} Private Function Generateproperties ($columns) {$keys = Array_keys ($columns);            foreach ($keys as $key) {$prop = $this->transform ($key);            if ($this->shouldexcludeprop ($prop)) {continue;        } $this->writetofile ("Private $prop;", 1);    } $this->writenewline (); } Private Function GeneratesetTers ($columns) {foreach ($columns as $key = = $value) {$prop = $this->transform ($key);            if ($this->shouldexcludeprop ($prop)) {continue; } $method = ' Set '.            Ucfirst ($prop);            $this->writetofile ("Public function $method ($ $prop) {", 1); $this->writetofile (' $ '). "This-> $prop = $".            "$prop;", 2);            $this->writetofile ("}", 1);        $this->writenewline (); }} Private Function Generatevalidateconfig ($table, $columns) {$this->writetofile (' private static $_valid Ator = Array (', 1); $this->writetofile ("' $table ' = = Array (", 2); foreach ($columns as $key = = $value) {$this-&GT;WR  Itetofile ("' $key ' = = Array (", 3); foreach ($value as $k = + $v) {if (is_string ($v)) {$this->writetofile ("' $k ' = ' $v ', ", 4);} else {$this->writetofile ("' $k ' = = $v,", 4);}} $this->writetofile ("),", 3);} $this->writetofile ("),//$table", 2); $this->writetofiLe ('); ', 1); $this->writenewline ();    } Private Function Getmin ($max, $type) {if (!isset ($max)) {return null;    } $min = self::D efault_min;    if ($type = = ' Date ' | | $min > $max) {$min = $max;    } return $min;        The Public Function Gettablecolumns ($table) {$fields = Mysql_list_fields ($this->database, $table);        $count = Mysql_num_fields ($fields);        if (! isset ($fields)) {die ("Failed-Get Fields". Mysql_error ());        } $columns = Array ();            for ($i = 0; $i < $count; $i + +) {$flags = Mysql_field_flags ($fields, $i);            $isRequired = Preg_match ('/not_null/', $flags);            $col = Mysql_field_name ($fields, $i);            $max = Mysql_field_len ($fields, $i);            $type = Mysql_field_type ($fields, $i);                        $min = $this->getmin ($max, $type); $columns [$col] = Array (' isrequired ' + = $isRequired, ' Max ' =&GT        $max, ' min ' = = $min, ' type ' and ' = $type, ');        } $sortedColumns = Array ();        $keys = Array_keys ($columns);        Sort ($keys);        foreach ($keys as $key) {$sortedColumns [$key] = $columns [$key];    } return $sortedColumns;    } Private Function Gettables () {$sql = "SHOW TABLES from {$this->database}";    $result = mysql_query ($sql);    $tables = Array ();    for ($i = 0; $i < mysql_num_rows ($result); $i + +) {$tables [] = Mysql_tablename ($result, $i);    } return $tables;    } Private Function Shouldexcludeprop ($prop) {if (! isset ($this->excludedproperties)) {return false;        } $index = Array_search ($prop, $this->excludedproperties);    Return Is_int ($index);        } Private Function transform ($name) {$words = explode (' _ ', $name);        $newName = null;         foreach ($words as $word) {if ($newName = = null) {       $newName = $word;            } else {$newName. = Ucfirst ($word);    }} return $newName;    } Private Function Writenewline () {$this->writetofile (");        } Private Function WriteToFile ($str, $count = 0) {$space = null;        $count *= self::D efault_indent;            while ($count) {if ($space = = null) {$space = ';            } else {$space. = ';        } $count--;        } fwrite ($this->file, $space);    Fwrite ($this->file, "$STR \ n"); }}//Tableclassgenerator$gen = new Tableclassgenerator (Array (' excludedproperties ' = = Array (' id ', ' userId '), ' da Tabase ' + ' mydb ', ' host ' = ' localhost ', ' parentclass ' = ' Base ', ' password ' = ' pwd ',//' Tables    ' = = Array (' user '), ' user ' = ' userId ',)); $gen->generateclasses ();
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.