PHP Classes

File: generateFile.php

Recommend this page to a friend!
  Classes of Martijn Waeyenbergh   PHP MySQL Generator   generateFile.php   Download  
File: generateFile.php
Role: Application script
Content type: text/plain
Description: generate the data File
Class: PHP MySQL Generator
Generate classes to access MySQL database tables
Author: By
Last change: some bug fixing:
- default value not set
- autoupdate on datefields (eg. autoupdate 'updated field' with CURRENT_TIMESTAMP
Date: 1 year ago
Size: 7,758 bytes
 

Contents

Class file image Download
<?php

include_once('class.field.php');
session_start();


function
genereerCLASS($classname,$comments){
   
$template = file_get_contents("./sourceData/classTemplate.php");
   
$template = str_replace("#classname#", $classname,$template);
   
$template = str_replace("#comments#", $comments,$template);
   
$fieldoutput = "";
    foreach (
$_SESSION['fields'] as $field) {
       
$fieldoutput .= "\tpublic $". $field->name . ";".PHP_EOL;
    }
   
$template = str_replace("#classvars#", $fieldoutput,$template);
    return
$template;
}


/*
geneer een databank classe specifiek voor deze php class...
-> getAll
-> getbyField
-> update(class)
-> delete
-> insert(class)
*/
function maakDBCLASS($classname,$comments){

   
$foundKeys = "";
   
$output ="<?php ".PHP_EOL.PHP_EOL;
   
$output .= "/*".$comments."*/".PHP_EOL.PHP_EOL;
   
$output .= "require_once('class.databank.php');".PHP_EOL;
   
$output .= "require_once('class.".$classname.".php');".PHP_EOL.PHP_EOL;
   
$output .= "class ".$classname."DB extends databank{".PHP_EOL.PHP_EOL;


   
/*************************
            CONSTRUCT
    *************************/

   
$output .= "\t".'public function __construct(){
        parent::__construct();
        $sql = "
            CREATE TABLE IF NOT EXISTS `'
.$classname.'` ('.PHP_EOL;

   
$fieldoutput = "";
            foreach (
$_SESSION['fields'] as $field) {
                if (
$field->isnullable == "Nullable"){
                   
$nullable = "NULL";
                }else{
                   
$nullable = "NOT NULL";
                }
                if (empty(
$field->isdefault)){
                   
$default = "";
                }else{
                    if (
$field->isdefault == "CURRENT_TIMESTAMP"){
                       
$default = "default " . $field->isdefault . "";
                    }else{
                       
$default = "default '" . $field->isdefault . "'";
                    }
                }
                if (
$field->isautoupdate == "Autoupdate"){
                   
$autoupdate = "ON UPDATE CURRENT_TIMESTAMP";
                }else{
                   
$autoupdate = "";
                }
                if (
$field->iskey == "Key"){
                   
$key = "AUTO_INCREMENT";
                   
$foundKeys = $field->name;
                }else{
                   
$key = "";
                }
               
//
               
$fieldoutput .= "\t\t\t\t`" . $field->name . "` " . $field->istype . " " . $default . " " . $nullable . " " . $autoupdate . " " . $key . ",".PHP_EOL;
            }
            if (empty(
$foundKeys)){
               
$fieldoutput = PHP_EOL."\t\t\t\t`id` int(11) NOT NULL AUTO_INCREMENT,".PHP_EOL . $fieldoutput;
               
$fieldoutput = $fieldoutput . "\t\t\t\tPRIMARY KEY (`id`)";
            }else{
               
$fieldoutput = $fieldoutput . "\t\t\t\tPRIMARY KEY (`".$foundKeys."`)";
            }
       
       
$output .= $fieldoutput.PHP_EOL;


       
$output .= "\t\t\t".') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;";
        try {
            $connection = $this->connect();
            $connection->exec($sql);
            return true;
        }catch (PDOException $e) {
            return false;
        }
    }'
.PHP_EOL.PHP_EOL;


   
/*************************
            INSERT
    *************************/

   
$foundKeys = "";
   
$paramBind = "";
   
$fieldList = "";
   
$output .= "\t".'public function insertAsObject($object){'.PHP_EOL;
   
$output .= "\t\t".'$connection = $this->connect();
                $stmt = $connection->prepare("insert into '
.$classname.' values(';
                    foreach (
$_SESSION['fields'] as $field) {
                        if (
$field->iskey == "Key"){
                           
$fieldList .= "null,";
                           
$foundKeys = "true";
                        }else{
                           
$fieldList .= ":" . $field->name . ",";
                           
$paramBind .="\t\t".'$stmt->bindParam(":'.$field->name.'", $object->'.$field->name.');'.PHP_EOL;
                        }
                       
                    }
                    if (
$foundKeys == ""){
                       
$output .= "null," . substr($fieldList, 0, -1);
                    }else{
                       
$output .= substr($fieldList, 0, -1);
                    }
                   
                   
$output .= ');");';


   
$output .= PHP_EOL.$paramBind . "\t\t".'return $stmt->execute();'.PHP_EOL;
   
$output .= "\t".'}'.PHP_EOL.PHP_EOL;


   
/*************************
            GET ALL
    *************************/


   
$output .= "\t".'public function getAll(){
        $connection = $this->connect();
        $sql = "SELECT * FROM '
.$classname.'";
        $result = $connection->query($sql);
        return $result->fetchAll(PDO::FETCH_OBJ);
    }'
.PHP_EOL.PHP_EOL;

   
/*************************
            GET BY Key
    *************************/
   
$key = "";
    foreach (
$_SESSION['fields'] as $field) {
            if (
$field->iskey == "Key"){
               
$key = $field;
            }
        }
   
$output .= "\t".'public function getByKey($key){
        $connection = $this->connect();
        $stmt = $connection->prepare("SELECT * FROM '
.$classname.' WHERE '.$key->name.' = :id");
        $stmt->bindParam(":id", $key);
        $stmt->execute();
        return $stmt->fetchObject("'
.$classname.'");
    }'
.PHP_EOL.PHP_EOL;

   
/*************************
            UPDATE
    *************************/
   
$paramBind = "";
   
$key = "";
   
$output .= "\t".'public function update($object){
        $connection = $this->connect();
        $sql= "update '
.$classname .' set ';
        foreach (
$_SESSION['fields'] as $field) {
            if (
$field->iskey != "Key"){
               
$output .= $field->name.' = :'.$field->name.',';
            }else{
               
$key = $field;
            }
        }
       
$output = substr($output, 0, -1);
       
$output .= ' where '.$key->name.'= :'.$key->name.'";'.PHP_EOL;

       
$output .= "\t\t".'$stmt = $connection->prepare($sql);'.PHP_EOL;

        foreach (
$_SESSION['fields'] as $field) {
           
$paramBind .="\t\t".'$stmt->bindParam(":'.$field->name.'", $object->'.$field->name.');'.PHP_EOL;
        }
   
$output .= $paramBind;
   
$output .= "\t\t".'return $stmt->execute();'.PHP_EOL;
   
$output .= "\t".'}'.PHP_EOL.PHP_EOL;



   
/*************************
        DELETE
    *************************/

   
$key = "";
    foreach (
$_SESSION['fields'] as $field) {
            if (
$field->iskey == "Key"){
               
$key = $field;
            }
        }
   
$output .= "\t".'public function delete($id){'.PHP_EOL;

           
$output .= "\t\t".'$connection = $this->connect();'.PHP_EOL;
       
$output .= "\t\t".'$stmt = $connection->prepare("DELETE FROM '.$classname .' WHERE '.$key->name.' = :'.$key->name.'"); '.PHP_EOL;
       
$output .= "\t\t".'$stmt->bindParam(":'.$key->name.'", $id);'.PHP_EOL;
       
$output .= "\t\t".'$stmt->execute();'.PHP_EOL;

   
$output .= "\t".'}'.PHP_EOL.PHP_EOL;
   
   
   
$output .= "}".PHP_EOL;
   
$output .= "?>";
    return
$output;

}

//$tmpName = "./class.".$_POST['classname'].".php";
//file_put_contents($tmpName, genereerCLASS($_POST['classname'],$_POST['comments']));
file_put_contents("output/class.".$_POST['classname'].".php", genereerCLASS($_POST['classname'],$_POST['comments']));
file_put_contents("output/class.".$_POST['classname']."DB.php", maakDBCLASS($_POST['classname'],$_POST['comments']));



/*
copieer ook de DATabank klasse zelf mee...
*/
copy("./sourceData/class.databank.php", "./output/class.databank.php");







// Get real path for our folder
$rootPath = realpath('output');

// Initialize archive object
$zip = new ZipArchive();
$tijd = date("U");
$zip->open("./zips/".$_POST['classname'].$tijd.'.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new
RecursiveDirectoryIterator($rootPath),
   
RecursiveIteratorIterator::LEAVES_ONLY
);

foreach (
$files as $name => $file)
{
   
// Skip directories (they would be added automatically)
   
if (!$file->isDir())
    {
       
// Get real and relative path for current file
       
$filePath = $file->getRealPath();
       
$relativePath = substr($filePath, strlen($rootPath) + 1);

       
// Add current file to archive
       
$zip->addFile($filePath, $relativePath);
    }
}
echo
"Zip file created: " . $zip->numFiles . " files in zip<br>";
// Zip archive will be created only after closing object
$zip->close();

echo
"<a href='./zips/".$_POST['classname'].$tijd.".zip''>download zip file</a>";

// delete all files in the output folder (cleanup)


?>