#1 klboy
function modelcreate(){每次新建数据库表后,又要在model创建模型类,感觉重复操作,虽然只是几行代码,但是每次创建不是很爽,写了这个自动创建的函数,把这个函数放入一个自定义文件,存放在include文件夹,然后在主配置文件index.php spRun()之前加入import('modelcreate.php');
$server=$GLOBALS['G_SP']['db']['host'];
$user=$GLOBALS['G_SP']['db']['login'];
$pass=$GLOBALS['G_SP']['db']['password'];
$dbname=$GLOBALS['G_SP']['db']['database'];
$conn=mysql_connect($server,$user,$pass);
if(!$conn) die("数据库系统连接失败!");
$result=mysql_list_tables($dbname);
if(!$result) die("数据库连接失败!");
$row=mysql_fetch_row($result);
foreach ($row as $k=>$v){
$sql = "describe $v";
$re=mysql_query($sql);
while($rowzj = mysql_fetch_array($re)){
if($rowzj['Key']=='PRI'){
$zjarray[]= $rowzj['Field'];
break;
}
}
}
mysql_free_result($result);
mysql_close($conn);
$modeldir = $GLOBALS['G_SP']['model_path'];
$temp = scandir($modeldir);
if(is_array($temp)){
array_shift($temp);
array_shift($temp);
if(empty($temp)){
foreach($row as $k=>$v){
$data = 'class lib_'.$v.' extends spModel
{
var $pk = "'.$zjarray[$k].'";//主键
var $table = "'.$v.'";//数据库名称
}';
$file = $modeldir."/lib_$v.php";
file_put_contents($file,$data);
}
}else{
foreach ($temp as $v){
preg_match_all('/lib_(.*).php/',$v,$match);
$libarray[]= $match[1][0];
}
foreach ($row as $k=>$v){
if(!in_array($v,$libarray)){
$data = 'class lib_'.$v.' extends spModel
{
var $pk = "'.$zjarray[$k].'";//主键
var $table = "'.$v.'";//数据库名称
}';
$file = $modeldir."/lib_$v.php";
file_put_contents($file,$data);
}
}
foreach ($libarray as $v){
if(!in_array($v,$row)){
$delfile = $modeldir."/lib_$v.php";
@unlink($delfile);
}
}
}
}
}
随便找个地方调用一下modelcreate();就自动同步数据库表创建模型类了。如果已经创建过的不会影响,如果数据库没有对应表的会自动删除多余的模型类
2014-08-12 17:37:41