phprap是一款开源的接口文档管理系统(http://www.phprap.com/),但是在使用的过程中发现为接口添加参数的过程效率比较低,得一个一个的添加参数,假设有是个参数,那得走十遍添加参数的流程,如下图:
根据配置时自动生成的表,发现接口相关的数据都是放在表xxx_api表中,而接口参数相关的放在xxx_field表中,field表中主要的字段是:api_id(对应放接口表中的id)、name(接口参数名称)、type(接口参数对应的数据类型)、is_required(是否必填)、default_value(参数默认值);
以上几个关键的参数中,除了默认值不太好设置外其余的都可以直接将数据库表中的属性转换成接口对应的参数,这里主要使用到sql语句:SHOW COLUMNS FROM `rap_field`,结果如下:
其中field对应xxx_field表中的name字段值,type对应xxx_field表中的type字段值(不过需要做下转换处理,因为两边的类型值不一致),Null对应的是xxx_field表中的is_required字段(同样需要转换):
把DB表字段转成接口参数的话,主要参数有api_id,database,tablename:接口代码处理如下:
$api_id = Yii::$app->request->post("api_id");$database = Yii::$app->request->post("database");
$tableName = Yii::$app->request->post("tablename");
$connection = new \yii\db\Connection([
'dsn' => "mysql:host=xxxx;dbname=xxxx",
'username' => "xxxx",
'password' => "xxxxxx",
]);
$connection->open();
$command = $connection->createCommand('SHOW COLUMNS FROM ' . $database . "." . $tableName);
$cols = $command->queryAll();
$connection->close();
$sql = "";
foreach($cols as $col)
{
$colType = preg_replace("/\([\d]+\)/","",$col["Type"]);
$type = ($colType == "int" || $colType == "tinyint") || $colType == "smallint" ? "number" : "string";//大致处理了下,还有很多类型没列举的
$require = $col["Null"] == "NO" ? 1 : 0;
$sql .= "insert into xxxx.xxxx_field(api_id,user_id,parent_id,`name`,title,`type`,method,is_required)values($api_id,1,0,'". $col["Field"] ."','". $col["Field"] ."','". $type."',1,$require);";
}
$con = \Yii::$app->get('xxxxxx');
$cmd = $con->createCommand($sql);
$cmd->execute();
phprap系统代码中可以在接口主页添加一个表单提交,接口调用成功后直接刷新页面