【问题标题】:laravel create model from custom stub when using php artisanlaravel 在使用 php artisan 时从自定义存根创建模型
【发布时间】:2018-07-01 06:43:33
【问题描述】:

当我使用php artisan make:model CustomNamespace\TestModel 时,我得到一个基于默认存根的模型:

namespace App\Models\CustomNamespace;
use Illuminate\Database\Eloquent\Model;
class TestModel extends Model
{
    //
}

但是我想要创建的是一个基于我自己的存根的动态模型来获得类似这样的东西:

namespace App\Models\CustomNamespace;

use App\Models\MyParent;
/**
 * Put a dynamic doc here
 */
class MyModel extends MyParent
{
    /*put custom methods here*/
}

我检查了 Laravel 文档和其他教程,但没有任何内容,你能帮助大家吗?

【问题讨论】:

  • 你成功了吗?

标签: laravel model laravel-artisan stub


【解决方案1】:

从 Laravel 7 开始,你可以通过运行申请stub customization

php artisan stub:publish

此命令将在应用程序根目录的stubs 目录中发布用于artisan make 命令的所有存根文件,并让您能够根据项目的需要更改它们。

其中一个是stubs/model.stub

<?php

namespace {{ namespace }};

use Illuminate\Database\Eloquent\Model;

class {{ class }} extends Model
{
    //
}

改成:

<?php

namespace {{ namespace }};

use App\Models\MyParent;

/**
 * Put your documentation here
 */
class {{ class }} extends MyParent
{
    /* Put your custom methods here */
}

您可以在this blog post 中阅读更多关于存根自定义的信息。

【讨论】:

    【解决方案2】:

    创建一个新命令,扩展Illuminate\Foundation\Console\ModelMakeCommand 类并覆盖getStub() 方法:

    protected function getStub()
    {
        if ($this->option('pivot')) {
            return __DIR__.'/stubs/pivot.model.stub';
        }
    
        return storage_path('/stubs/my-own-model.stub');
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 2015-10-31
      • 1970-01-01
      • 2021-07-12
      • 2016-09-12
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多