Skip to content

Instantly share code, notes, and snippets.

@vpadhariya
Last active August 10, 2017 08:16
Show Gist options
  • Save vpadhariya/0c6e01cd05f084e406c4 to your computer and use it in GitHub Desktop.
Save vpadhariya/0c6e01cd05f084e406c4 to your computer and use it in GitHub Desktop.
Yii2 Generate Base models (put this file into your yii2 project under console/controller/GenerateBaseModelsController.php) and run php yii generate-base-models
<?php
namespace console\controllers;
use Yii;
/**
* Controller to Generate base models
* NOTE : make sure you are using Development Environment.
* @author digitize
*/
class GenerateBaseModelsController extends \yii\console\Controller
{
/**
* Array of tables to be skipped
* @var Array
*/
var $skip_tables = ['migration', 'log', 'session', 'message', 'source_message', 'auth_assignment', 'auth_item', 'auth_item_child', 'auth_rule'];
/**
* Start time for script execution
* @var string
*/
var $startTime;
/**
* Echoes this filename on screen just for output purpose
* @var string
*/
var $thisFile;
/**
* Index method
*/
public function actionIndex()
{
$this->startTime = time();
$this->thisFile = basename(__FILE__);
echo "\n" . 'SCRIPT `' . $this->thisFile . '` START AT: ' . Yii::$app->formatter->asDatetime('now', 'php:l d. F Y H:i:s A') . "\n\n";
$tables = Yii::$app->db->schema->getTableNames();
foreach($tables as $table)
{
if(in_array($table, $this->skip_tables)) continue;
$tableName = $table;
$modelClass = self::tableToModelClass($table);
$command = 'php yii gii/model --tableName=' . $tableName; // For table name
$command .= ' ' .'--modelClass=' . $modelClass; // Model class name
$command .= ' ' .'--baseClass=common\models\SHSActiveRecord'; // Extend class name
$command .= ' ' .'--generateRelations=all'; // Generate relation
$command .= ' ' .'--overwrite=1'; // Overwrite existing class
$command .= ' ' .'--ns=\common\models\base'; // Define namespace
$command .= ' ' .'--useTablePrefix=0'; // Use table prefefix
$command .= ' ' .'--interactive=0'; // Interactive output
$command .= ' ' .'--enableI18N=1'; // Enable I18N
exec(escapeshellcmd($command), $output);
echo implode($output, "\n");
}
$endTime = time() - $this->startTime;
echo "\n" . 'TIME TAKEN TO EXECUTE SCTIPT : ', $endTime . '(' . round($endTime / 60, 3) . ') Seconds(Minutes)';
echo "\n" . Yii::$app->formatter->asDatetime('now', 'php:H:i:s'), ' : FILE `' . $this->thisFile . '` EXECUTED SUCESSFULLY', "\n\n";
}
/**
* Generate model name base on Table
* If table name is "tbl_user" the class generated will be "baseUser"
*/
private function tableToModelClass($table)
{
$tbl_name_parts = explode('_', $table);
$tableName = 'base';
for($i=0; $i <= count($tbl_name_parts); $i++)
{
if(Yii::$app->db->tablePrefix == $tbl_name_parts[$i]) continue;
$tableName .= ucWords($tbl_name_parts[$i]);
}
return $tableName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment