12/02/2018 3:34 WIB | Generator
Make Your Own Code Generator

After long time using php on my daily job, i realize i need to  make my own code generator to do my own job.

In my daily activities, I used to use php native compared to php framework. But the disadvantage is that I have to rewrite frequently used codes.

Then I thought, why not make my own generator?

In this example, I have the following script:
1. read the database,
2. reading the table columns,
3. generate CRUD code
4. code output in a folder, save code as php

Read Database
The generator will need credential to access database, such as: username, password and database name. As usual, we make connection.

$host = 'localhost';
$db   = 'YOUR_DATABASE_NAME';
$user = 'YOUR_USERNAME_TO_ACCESS_DB';
$pass = 'YOUR_PASS_TO_ACCESS_DB';
$charset = 'utf8';
    

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
GLOBAL $pdo,$db;

After connection built successful, we need make a basic function to Read Table, Fetch Columns,  Create File (generate to php) etc.

BASIC FUNCTION

function list_tables()
{
    global $pdo;
    $sql = 'SHOW TABLES';
     $q = $pdo->query($sql);
    $z = $q->fetchAll(PDO::FETCH_COLUMN);
    return $z;
}
function list_kolom($table)
{
     global $pdo, $db;
    $sql ="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$db' AND TABLE_NAME = '$table'";
     global $pdo;
     $q = $pdo->query($sql);
    $z = $q->fetchAll(PDO::FETCH_COLUMN);
    return $z;
    
}

function safe($str)
{
    return strip_tags(trim($str));
}

function readJSON($path)
{
    $string = file_get_contents($path);
    $obj = json_decode($string);
    return $obj;
}

function createFile($string, $path)
{
    $create = fopen($path, "w") or die("Change your permision folder for application and harviacode folder to 777");
    fwrite($create, $string);
    fclose($create);
    
    return $path;
}

function label($str)
{
    $label = str_replace('_', ' ', $str);
    $label = ucwords($label);
    return $label;
}

Above code is about how to access database description and schema using php, and also how to generate file we need, for future development.

Prepare Code
In this section, we gonna make a simple fetch database schema like columns and table, to a separate variable. Next, we use these variable to be filled to template we will create.

function rapihinjudul( $string ) {
    return str_replace( "_", " ", trim( strtoupper( $string ) ) );
}
function angkadoang( $string ) {
    return preg_replace( "/[^0-9]/", "", $string );
}
$kolom =  list_kolom($table);
$i = 0;
$param='';
$kol ='';
foreach($kolom as $k[$i]){


    $kol .= '`'.$k[$i].'`,';
    $param .= '$'.$k[$i].',';

    $i++;
}
$xparam = substr($param,4,-1);
$xkolom = substr($kol,5,-1);


$tab = str_replace('_','',$table);

//////////buat kolom insert 
$xxparam = explode(",",$xparam);
//$xxparam = str_replace(",","','",$xparam);
$xxp=1;
$xu = '';
foreach($xxparam as $xp[$xxp]){
    $xu .= "'".$xp[$xxp]."',";
    // $xxu .= str_replace("\''","\','",$xu);
    $xxp++;
}

Just use $xu to be applied on template, like this..

Example: Generate a php Function

<?php

$fungsi ="
<?php
/* 
****************************************************************************************************************
****************************************************************************************************************
.___             .__   __  .__                   
|   |_________ __|  |_/  |_|  |__   ____ _____   
|   \___   /  |  \  |\   __\  |  \_/ __ \\__  \  
|   |/    /|  |  /  |_|  | |   Y  \  ___/ / __ \_
|___/_____ \____/|____/__| |___|  /\___  >____  /
          \/                    \/     \/     \/ 
*	Nama		: GenZul Crud
* 	Author		: Izulthea
*	URL		: http://izulthea.com
* 	Description	: CRUD Buatan Sendiri
*	DISCLAIMER	: CAPEK CUY HEHEHEE
*   TANGGAL     : ".date('d-m-Y H:i a')."
****************************************************************************************************************
****************************************************************************************************************
*/		
 
include('../inc/koneksi.php');// change as you need
 
 function rapihinjudul( \$string ) {
    return str_replace( \"_\", \" \", trim( strtoupper( \$string ) ) );
}
function angkadoang( \$string ) {
    return preg_replace( \"/[^0-9]/\", \"\", \$string );
}

function api_".$tab."()
{
global \$pdo;
 \$array = \$pdo->query(\"SELECT * FROM ".$table."\")->fetchAll(PDO::FETCH_ASSOC);
 echo json_encode(array('data' =>\$array));

}
function api_cari_".$tab."(\$q)
{
global \$pdo;
 \$array = \$pdo->query(\"SELECT * FROM ".$table." WHERE provinsi  LIKE '%\$cari%'\")->fetchAll(PDO::FETCH_ASSOC);
 echo json_encode(array('data' =>\$array));

}
//gunakan ini buat custom query, contohnya by email
function api_".$tab."_byemail(\$email)
{
global \$pdo;
 \$array = \$pdo->query(\"SELECT * FROM ".$table." WHERE Email ='\$email'\")->fetchAll(PDO::FETCH_ASSOC);
 echo json_encode(array('data' =>\$array));

}
function api_".$tab."_byid(\$id)
{
global \$pdo;
 \$array = \$pdo->query(\"SELECT * FROM ".$table." WHERE id ='\$id'\")->fetchAll(PDO::FETCH_ASSOC);
 echo json_encode(array('data' =>\$array));

}

 function hitung_".$tab."()
     {
        global \$pdo;
        \$sql = \"SELECT * FROM ".$table."\";
        \$q = \$pdo->query(\$sql);
        \$h = \$q->rowCount();
        return \$h;
     }
 function readAll_".$tab."()
    {
        global \$pdo;
        \$sql = \"SELECT * FROM ".$table." ORDER BY id DESC\";
        \$q = \$pdo->query(\$sql);

        return \$q;
    }
     function readDetil_".$tab."(\$id)
    {
        global \$pdo;
        
          \$sql= \"SELECT * FROM ".$table." WHERE id = :id\"; 
    \$stmt = \$pdo->prepare(\$sql);
    \$stmt->bindParam(':id', \$id, PDO::PARAM_INT); 
    \$stmt->execute();
    \$obj = \$stmt->fetchObject();
    return \$obj;

    }
    
function insert_".$tab."(".$xparam.")
    {
        global \$pdo;
        \$sql = \"INSERT INTO ".$table." (`id`,".$xkolom.") VALUES('?',".$xu.")\";
        \$q = \$pdo->query(\$sql);
        if(\$q)
        {
        echo '<script>alert(\"Data MAsuk\");</script>';
        }
    }
    /////// ubah aja
    function update_".$tab."(\$email)
    {
        global \$pdo;
        \$sql = \"UPDATE ".$table." SET email = '\$email'\";
        \$q = \$pdo->query(\$sql);
        if(\$q)
        {
        echo '<script>alert(\"Data Update\");</script>';
        }
    }
    
      function delete_".$tab."(\$email)
    {
        global \$pdo;
        \$sql = \"DELETE FROM ".$table." WHERE email = '\$email'\";
        \$q = \$pdo->query(\$q);
        if(\$q)
        {
        echo '<script>alert(\"Data Dihapus\");</script>';
        }
    }
?>
";

Above code, we have $fungsi variable, that is in string format. And variable like $xkolom that we have created before.

Put All Together

/* list of template we have created - start here */
include("modul/umum.php");
include("modul/koneksi.php");
include("modul/fungsi.php");
include("modul/view-data.php");
include("modul/view-detil.php");
include("modul/api.php");
include("modul/form.php");    
/* list of template we have created - end here */  


/* now execute to create php file to folder "outputnya" */

$fungsinya = createFile($fungsi, "outputnya/inc/fungsi_".$tab.".php");
$buat_view = createFile($datatable, "outputnya/view/view_".$tab.".php");
$detil_view = createFile($detil, "outputnya/view/detil_".$tab.".php");
$con = createFile($koneksi, "outputnya/inc/koneksi.php");
$ngapi = createFile($buat_api, "outputnya/api/api.php");
$ngform = createFile($form, "outputnya/view/form_".$tab.".php");


/* echo them on display */
echo "-----------------OUTPUT-----------------------<br>";
echo "<ul>";
echo "<li>Tampil (datatable) <a href='outputnya/view/view_".$tab.".php' target='_blank'>".$buat_view."...OK</a></li>";
echo "<li>DETIL <a href='outputnya/view/detil_".$tab.".php?id=1' target='_blank'>".$detil_view."...OK</a></li>";
echo "<li>FORM <a href='outputnya/view/form_".$tab.".php' target='_blank'>".$ngform."...OK</a></li>";
echo "<li>REST <a href='outputnya/api/api.php?cmd=all' target='_blank'>API/WEBSERVICE...OK</a></li>";

echo "<li>FUNCTION ".$fungsinya."...OK</li>";
echo "<li>KONEKSI ".$con."...OK</li>";
echo "</ul>";
echo "-----------------".date('d-m-Y') . " Jam " .date('H:i a')."-----------------------";

Finally, Create a Generator

<?php
date_default_timezone_set("Asia/Jakarta");
error_reporting(0);
require("c.php");
$table = $_POST['table'];



 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" media="screen" href="assets/css/bootstrap.min.css">

    <title>CRUD GENERATOR</title>
 

</head>

<body>
 <div class="container">
    <div class="row">
     
     
<h1>CRUD GENERATOR By Izulthea</h1>

        <div class="col-md-6">
       <div class="alert alert-info"><ol>
          <li>cocokkan username, password dan nama database pada <label class="label label-success">file c.php</label></li>
          <li>Table harus ada <label class="label label-danger"> kolom id auto increament</label></li>
          <li>gunakan dropdown table</li><li>tekan generate</li></ol>
            </div> 
    <form action="" method="post" class="form-inline">
        <select name="table" class="form-control">
    <?php 
    
$q = list_tables();
$i=0;
foreach($q as $z[$i]){
    echo '<option value="'.$z[$i].'">'.$z[$i].'</option>';
    $i++;
}
    ?>
    
    
    </select>
        <input role="button" class="btn btn-danger" type="submit" name="generate" value="generate">
    </form>
        
       
</div>
        <div class="col-md-6">
    
<?php 
if(ISSET($_POST['generate']))
{
include("core.php");
  
  }
?>
     
     </div>
     </div>
     
     </div>
    
 
</body>
</html>

Conclusion
To make your own code, you just need:
1. database connection (user,dbname, pass)
2. function to create file (php function)
3. folder to store output (if in live server, make sure you have chmod 777 that folder).
4. You can make varies of code you need, like FORM, HTML, JS, even Java.

Demo



Other Topics