Laravel 框架生成模型 property 注释
背景:
- 在
Hyperf框架中使用命令创建模型前,如果数据表存在,就会自动生成property注释。有property注释的模型,结合 IDE 扩展,就可以实现属性提示功能,开发起来很爽 - 使用
Laravel框架开发时,却没有找到相似功能,就很想实现类似注释,于是上头大哥就给我推荐了这个
实现原理:
- 在
laravel框架中创建一个Artisan命令行 - 在命令的实现中,通过数据表名来获取结构与字段类型,然后循环字段并根据类型匹配对应的 PHP 语法类型来拼接注释
- 打印拼接好的注释到屏幕以供使用
实现步骤:
- 执行命令
php artisan make:command GeneratModelAnnotation生成命令类,会创建一个app/Console/Commands/GeneratModelAnnotation.php文件 - 复制下方
↓代码到GeneratModelAnnotation.php文件,此时,就完成了新命令的创建工作 - 最后使用格式为
php artisan gma TableName的命令生成注释代码,TableName为表名。如果要为表名为admin_users,那就执行php artisan gma admin_users。如下:
root@62d044ee2a7e:/var/www/test.love.com# php artisan gma admin_users
* @property int $id
* @property string $username
* @property string $password
* @property string $name
* @property string $avatar
* @property string $remember_token
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
文件代码:
GeneratModelAnnotation.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* 生成模型property注释
* Class GeneratModelAnnotation
*
* @package App\Console\Commands
*/
class GeneratModelAnnotation extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'GMA {tableName}';
/**
* The console command description.
*
* @var string
*/
protected $description = '生成模型property注释,使得IDE有模型属性提示!';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
$tableName = $this->argument('tableName');
$dbName = config('database');
$columns = DB::select("
SELECT COLUMN_NAME, DATA_TYPE , COLUMN_COMMENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '{$tableName}'
AND table_schema = '{$dbName['connections']['mysql']['database']}'");
$annotation = "";
foreach ($columns as $column) {
$type = 'string';
if (in_array($column->DATA_TYPE, ['int', 'tinyint', 'smallint', 'mediumint', 'bigint'])) {
$type = 'int';
} elseif (in_array($column->DATA_TYPE, ['float', 'double', 'decimal'])) {
$type = 'float';
}
$columnName = $column->COLUMN_NAME;
if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at'])) {
$type = '\\Carbon\\Carbon';
}
$columnComment = $column->COLUMN_COMMENT;
$annotation .= sprintf("\n * @property %s \$%s %s", $type, $columnName, $columnComment);
}
$annotation .= "\n";
echo($annotation);
// file_put_contents('annotation',$annotation);
}
}
友情提示:
1、有现成扩展 ide-helper 实现了该功能,使用命令如下 php artisan ide-helper:models "App\Models\User"

731

被折叠的 条评论
为什么被折叠?



