rayvenues/eloquent-model-generator

Eloquent 模型生成器

v1.0.2 2023-06-09 17:17 UTC

This package is auto-updated.

Last update: 2024-09-13 23:04:17 UTC


README

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

版本 1.0.0

版本 1.0.0 已经发布。

安装

步骤 1. 配置您的数据库连接。运行您的迁移。

步骤 2. 将 Eloquent 模型生成器添加到您的项目中

composer require rayvenues/eloquent-model-generator --dev

用法

使用

php artisan ray:generate:model User

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

表名

使用 --table-name 选项指定另一个表名

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

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

输出路径

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

php artisan ray: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 ray:generate:model User --base-class-name=Custom\\Base\\Model

无备份

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

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

无时间戳

如果您想禁用模型的时间戳,请指定 --no-timestamps 选项

php artisan ray:generate:model User --no-timestamps

日期格式

如果您想为模型指定日期格式,请指定 --date-format 选项

php artisan ray:generate:model User --date-format='Y-m-d'

连接

如果您想指定模型的数据库连接名称,请指定 --connection 选项

php artisan ray:generate:model User --connection='mysql'

覆盖默认选项

您不必在每次执行命令时指定选项,而是可以通过执行以下命令来发布配置文件

php artisan vendor:publish --provider="Ray\EloquentModelGenerator\Provider\GeneratorServiceProvider"

这将创建一个名为 eloquent_model_generator.php 的文件,位于项目的 config 目录中。您可以修改该文件以使用自己的默认值

<?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,
    `role_id`  int(10) unsigned NOT NULL,
    `username` varchar(50)      NOT NULL,
    `email`    varchar(100)     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 ray:generate:model User

结果

App\Models\User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * @property integer $id
 * @property integer $role_id
 * @property string $username
 * @property string $email
 * @property Role $role
 */
class User extends Model
{
    /**
     * @var array
     */
    protected $fillable = ['role_id', 'username', 'email'];

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

为所有表生成模型

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

跳过表

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

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

或指定由逗号分隔的表名字符串

php artisan ray:generate:models --skip-table="users,roles"

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

自定义

您可以通过添加自己的 Ray\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);
        
        $propertyModel = new PropertyModel('guarded', 'protected', []);
        $dockBlockModel = new DocBlockModel('¡Tengo miedo!.', '@var array');
        $propertyModel->setDocBlock($dockBlockModel);
        $model->addProperty($propertyModel);

    }

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

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

在你的服务提供者中

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

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

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

/**
 * ¡Tengo miedo!.
 * 
 * @var array
 */
protected $guarded = [];
...

注意

处理器优先级非常重要。优先级0是最高的。优先级越高,处理器被调用的越晚。

默认处理器优先级

  • TableNameProcessor - 0
  • ClassDefinitionProcessor - 18
  • NamespaceProcessor - 1
  • BaseClassProcessor - 2
  • CustomPrimaryKeyProcessor - 3
  • SoftDeleteTraitProcessor - 4
  • DateFormatProcessor - 5
  • ConnectionProcessor - 6
  • NoBackupProcessor - 7
  • PropertyProcessor - 8
  • RelationProcessor - 9
  • DocBlockProcessor - 10
  • FillableProcessor - 11
  • PrimaryKeyProcessor - 12
  • TimestampsProcessor - 13
  • TableNameProcessor - 14
  • BackupProcessor - 15
  • ModelProcessor - 16
  • UseStatementProcessor - 17
  • NamespaceDirectoryProcessor - 19