在開發 MVC 框架或 ORM 模型時,手寫類屬性既繁瑣又易出錯。利用 MySQL information_schema.COLUMNS 表,可自動獲取欄位名、類型、註釋,生成標準的 PHP 類屬性代碼(含 PHPDoc 註釋、駝峰命名轉換)。本文提供一個開箱即用的生成器腳本。
<?php
/**
* 資料表結構轉 PHP 模型類屬性生成器
* 用法:php gen_model.php --table=users --namespace=App\\Models
*/
require_once 'vendor/autoload.php'; // 假設使用 Composer 載入 DB 連接
// 簡易參數解析
$options = getopt('', ['table:', 'namespace:', 'prefix:', 'output:']);
$table = $options['table'] ?? '';
$namespace = $options['namespace'] ?? 'App\\Models';
$tablePrefix = $options['prefix'] ?? ''; // 表前綴,如 'tp_'
$outputFile = $options['output'] ?? 'php://stdout';
if (!$table) {
fwrite(STDERR, "Usage: php gen_model.php --table=table_name [--namespace=App\\Models] [--prefix=tp_] [--output=file.php]\n");
exit(1);
}
// 資料庫連接(這裡用 PDO 示例)
$pdo = new PDO(
"mysql:host=127.0.0.1;dbname=my_db;charset=utf8mb4",
'user', 'pass',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// 查詢欄位資訊
$sql = "
SELECT
COLUMN_NAME,
COLUMN_TYPE,
COLUMN_COMMENT,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION,
NUMERIC_SCALE,
IS_NULLABLE,
COLUMN_DEFAULT,
COLUMN_KEY
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :table
ORDER BY ORDINAL_POSITION
";
$stmt = $pdo->prepare($sql);
$stmt->execute([':table' => $table]);
$columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$columns) {
fwrite(STDERR, "表 `$table` 不存在或無欄位\n");
exit(1);
}
// 類名轉換:表名去前綴、下劃線轉駝峰、首字母大寫
$className = str_replace(' ', '', ucwords(str_replace('_', ' ', ltrim($table, $tablePrefix))));
$className = str_replace(' ', '', $className); // 再次確保無空格
// 生成屬性代碼
$properties = [];
foreach ($columns as $col) {
// 欄位名轉駝峰(屬性名)
$propName = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $col['COLUMN_NAME']))));
// PHP 類型提示推斷
$phpType = mapDbTypeToPhp($col['DATA_TYPE'], $col['COLUMN_TYPE']);
$nullable = $col['IS_NULLABLE'] === 'YES' ? '?' : '';
// 註釋
$comment = $col['COLUMN_COMMENT'] ?: $col['COLUMN_NAME'];
$comment = addcslashes($comment, "\n\r\t"); // 轉義換行
$properties[] = << {$outputFile}\n";
/**
* MySQL 資料類型映射到 PHP 類型
*/
function mapDbTypeToPhp(string $dataType, string $columnType): string {
$dataType = strtolower($dataType);
// 整數族
if (in_array($dataType, ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'])) {
return 'int';
}
// 浮點族
if (in_array($dataType, ['decimal', 'float', 'double', 'real'])) {
return 'float';
}
// 字符串族
if (in_array($dataType, ['char', 'varchar', 'text', 'tinytext', 'mediumtext', 'longtext', 'enum', 'set'])) {
return 'string';
}
// 二進制族
if (in_array($dataType, ['binary', 'varbinary', 'blob', 'tinyblob', 'mediumblob', 'longblob'])) {
return 'string'; // 或資源流,通常用 string 存 base64
}
// 日期時間族
if (in_array($dataType, ['date', 'datetime', 'timestamp', 'time', 'year'])) {
return '\\DateTimeInterface'; // 建議使用 DateTime 物件
}
// JSON
if ($dataType === 'json') {
return 'array|object|string'; // 實際為混合類型
}
// 布爾
if ($dataType === 'tinyint' && strpos($columnType, '(1)') !== false) {
return 'bool';
}
return 'mixed';
}
?>
表 tp_users 結構:
CREATE TABLE `tp_users` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶ID',
`user_name` varchar(50) NOT NULL DEFAULT '' COMMENT '用戶名',
`email` varchar(100) NOT NULL DEFAULT '' COMMENT '郵箱',
`password` char(60) NOT NULL DEFAULT '' COMMENT '密碼哈希',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '狀態 1正常 0禁用',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
執行 php gen_model.php --table=tp_users --prefix=tp_ --namespace=App\\Models 生成:
<?php
namespace App\Models;
class Users
{
/**
* 用戶ID
* @var int
*/
public int $id;
/**
* 用戶名
* @var string
*/
public string $userName;
/**
* 郵箱
* @var string
*/
public string $email;
/**
* 密碼哈希
* @var string
*/
public string $password;
/**
* 狀態 1正常 0禁用
* @var bool
*/
public bool $status;
/**
* 創建時間
* @var \DateTimeInterface
*/
public \DateTimeInterface $createdAt;
}
$table、$primaryKey、$fillable、$casts、關聯方法存根。TABLE_SCHEMA,遞歸生成多個模塊的模型。php artisan make:model-from-table users、或 PhpStorm Live Template。COLUMN_TYPE 解析長度、無符號、零填充等,生成更精確的 @property-read 或 #[Attribute]。information_schema.KEY_COLUMN_USAGE 獲取外鍵,自動生成 belongsTo/hasMany 方法存根。composer require --dev reliese/laravel → php artisan code:models --table=users(功能極其強大,支援關聯、索引、類型轉換)。php bin/doctrine orm:convert-mapping --from-database annotation ./src/Entity。