Automatically generate a PHP class based on the table structure

Source: Internet
Author: User
A php class Zendframework is automatically generated based on the table structure. a class and table ing method is provided to create a class that inherits Zend_Db_Table. During the query, zend automatically processes the table fields and generates an object. the object attributes are dynamically created, so they are public. Two PHP classes are automatically generated based on the table structure.

Zend framework provides a ing between class and table to create a class that inherits Zend_Db_Table. During the query, zend automatically processes the table fields and generates an object. the object attributes are dynamically created, so they are public. There are two major problems: first, the class attribute is public, and second, the class attribute is determined only after code execution. Therefore, I wrote a program to generate the corresponding class based on 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 ("Tables ($ this-> givenTables) in config is not an array or it is empty. ") ;}$ this-> parentClass = $ config ['parentclass']; if ($ config ['cludedproperties']) {$ this-> excludedProperties = $ config ['excludedproperties']; if (! Is_array ($ this-> excludedProperties) | empty ($ this-> excludedProperties) {die ('excludedproperties shocould be an array and shoudnot be empty. ') ;}} if (! File_exists (self: DEFAULT_DIR) {mkdir (self: DEFAULT_DIR) ;}} public function _ destroy () {mysql_close ();} public function generateClasses () {$ allTables = $ this-> getTables (); var_dump ($ allTables); $ tables = $ this-> givenTables? $ 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: DEFAULT_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 have 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-> writeToFil E ("?> "); 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' =>' $ prop',", 2) ;}$ this-> writeToFile (');', 1 ); $ this-> writeNewLine ();} private function generate Const ($ table) {$ this-> writeToFile ("const TABLE_NAME = '$ table';", 1); $ this-> writeNewLine ();} private function generateGetters ($ columns) {foreach ($ columns as $ key = >$ value) {$ prop = $ this-> 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) {$ pr Op = $ 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 $ _ validator = ar Ray (', 1); $ this-> writeToFile ("' $ table' => array (", 2); foreach ($ columns as $ key => $ value) {$ this-> writeToFile ("'$ 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 fu Nction getMin ($ max, $ type) {if (! Isset ($ max) {return null;} $ min = self: DEFAULT_MIN; if ($ type = 'Date' | $ min> $ max) {$ min = $ max;} return $ min;} public function getTableColumns ($ table) {$ fields = mysql_list_fields ($ this-> database, $ table ); $ count = mysql_num_fields ($ fields); if (! Isset ($ fields) {die ("Failed to 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' => $ is Required, 'Max' => $ max, 'min' => $ min, 'type' => $ 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 ++) {$ t Ables [] = 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: DEFAULT_INDENT; while ($ count) {if ($ space = null) {$ space = '';} else {$ space. = '';} $ count --;} fwrite ($ this-> file, $ space); fwrite ($ this-> file," $ str \ n ");}} // TableClassGenerator $ gen = new TableClassGenerator (array ('cludedproperties' => array ('id', 'userid'), 'database' => '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.