可怕代码/优雅模型生成器

v2.0.4-stable 2023-11-05 23:12 UTC

This package is auto-updated.

Last update: 2024-09-06 01:25:12 UTC


README

已更新最新 composer 依赖以兼容 Laravel 10,在 SQlite 和 Postgres 上进行了测试

即将推出:更好的 Postgres 支持 & 对贡献者的 CI/CD 支持。

优雅模型生成器使用数据库模式作为源来生成 Eloquent 模型。

版本 2.0.4

改进:分叉并更改命名空间,更新 Composer,添加 phpstan,添加 php-cs-fixer,更新到最新的 phpunit 版本

安装

步骤 1. 将优雅模型生成器添加到您的项目中

composer require dreadfulcode/eloquent-model-generator dev-2x --dev 

步骤 2. 确认 Dreadfulcode\EloquentModelGenerator\ProviderGeneratorServiceProvider

'providers' => [
    // ...
    Dreadfulcode\EloquentModelGenerator\Provider\GeneratorServiceProvider::class,
];

步骤 3. 配置您的数据库连接。

该项目使用 SQLite3 进行了测试。对于 Ubuntu 22.x 上的 Sqlite3 和 PHP 8.1:sudo apt-get install php8.1-sqlite3

使用

使用

php artisan dreadfulcode:generate:model User

来生成模型类。生成器将查找名为 users 的表并为其生成模型。

表名

使用 表名 选项来指定另一个表名

php artisan dreadfulcode:generate:model User --table-name=user

在这种情况下生成的模型将包含 protected $table = 'user' 属性。

输出路径

生成的文件将保存在您的应用程序的 app/Models 目录中,并默认具有 App\Models 命名空间。如果您想更改目的地和命名空间,请分别提供 output-pathnamespace 选项

php artisan dreadfulcode:generate:model User --output-path=/full/path/to/output/directory --namespace=Your\\Custom\\Models\\Place

output-path 可以是绝对路径或相对于项目 app 目录的相对路径。绝对路径必须以 / 开头

  • /var/www/html/app/Models - 绝对路径
  • Custom/Models - 相对路径,将转换为 /var/www/html/app/Custom/Models (假设您的项目 app 目录是 /var/www/html/app

基本类名称

默认情况下,生成的类将扩展自 Illuminate\Database\Eloquent\Model。要更改基本类,请指定 base-class-name 选项

php artisan dreadfulcode:generate:model User --base-class-name=Custom\\Base\\Model

无备份

如果 User.php 文件已经存在,它将被重命名为 User.php~ 并保存在同一目录中。除非指定了 no-backup 选项

php artisan dreadfulcode:generate:model User --no-backup

其他选项

有一些有用的选项可以定义多个模型属性

  • no-timestamps - 向模型添加 public $timestamps = false; 属性
  • date-format - 指定模型的 dateFormat 属性
  • connection - 指定模型的连接名称属性

覆盖默认选项

您可以在每次执行命令时指定选项,也可以在项目的 config 目录中创建一个名为 eloquent_model_generator.php 的配置文件,并使用自己的默认值

<?php

return [
    'namespace' => 'App',
    'base_class_name' => \Illuminate\Database\Eloquent\Model::class,
    'output_path' => null,
    'no_timestamps' => null,
    'date_format' => null,
    'connection' => null,
    'no_backup' => null,
    'db_types' => null,
];

注册自定义数据库类型

如果运行命令导致错误

[Doctrine\DBAL\DBALException]
Unknown database type <TYPE> requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it.

则意味着您必须在您的 config/eloquent_model_generator.php 中注册您的类型 <TYPE>

return [
    // ...
    'db_types' => [
        '<TYPE>' => 'string',
    ],
];

使用示例

user

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `role_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `role_id` (`role_id`),
  CONSTRAINT `user_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

命令

php artisan dreadfulcode:generate:model User

结果

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * @property int $id
 * @property int $role_id
 * @property mixed $username
 * @property mixed $email
 * @property Role $role
 * @property Article[] $articles
 * @property Comment[] $comments
 */
class User extends Model
{
    /**
     * @var array
     */
    protected $fillable = ['role_id', 'username', 'email'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo('Role');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function articles()
    {
        return $this->hasMany('Article');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

为所有表生成模型

命令 dreadfulcode:generate:models 将生成数据库中所有表的模型。它接受 dreadfulcode:generate:model 可用的所有选项,以及 skip-table 选项。

跳过表

指定一个或多个要跳过的表名

php artisan dreadfulcode:generate:models --skip-table=users --skip-table=roles

注意,如果已配置前缀,则必须指定不带前缀的表名。

自定义

您可以通过添加自己的 Dreadfulcode\EloquentModelGenerator\Processor\ProcessorInterface 实例并使用 GeneratorServiceProvider::PROCESSOR_TAG 标记来钩入模型生成过程。

假设您想覆盖 Eloquent 的 perPage 属性值。

class PerPageProcessor implements ProcessorInterface
{
    public function process(EloquentModel $model, Config $config): void
    {
        $propertyModel = new PropertyModel('perPage', 'protected', 20);
        $dockBlockModel = new DocBlockModel('The number of models to return for pagination.', '', '@var int');
        $propertyModel->setDocBlock($dockBlockModel);
        $model->addProperty($propertyModel);
    }

    public function getPriority(): int
    {
        return 8;
    }
}

getPriority 决定了处理器相对于其他处理器被调用的顺序。

在你的服务提供者中

public function register()
{
    $this->app->tag([InflectorRulesProcessor::class], [GeneratorServiceProvider::PROCESSOR_TAG]);
}

之后,生成的模型将包含以下代码

/**
 * The number of models to return for pagination.
 * 
 * @var int
 */
protected $perPage = 20;