【问题标题】:How can I add more to the code generated by Laravel Artisan?如何向 Laravel Artisan 生成的代码添加更多内容?
【发布时间】:2019-12-31 05:42:18
【问题描述】:

我想在我的资源控制器类声明上方包含一些注释代码,最好在使用php artisan make:controller MyController -resource 生成控制器时添加。即,我想在每个控制器文件的顶部添加路径别名:

/*
Verb            URI                     Action              Route Name              desc
GET             /photos                 index               photos.index            Display a listing of the resource.
GET             /photos/create          create              photos.create           Show the form for creating a new resource.
POST            /photos                 store               photos.store            Store a newly created resource in storage.
GET             /photos/{photo}         show                photos.show             Display the specified resource.
GET             /photos/{photo}/edit    edit                photos.edit             Show the form for editing the specified resource.
PUT/PATCH       /photos/{photo}         update              photos.update           Update the specified resource in storage.
DELETE          /photos/{photo}         destroy             photos.destroy          Remove the specified resource from storage.
*/

这纯粹是一个方便的示例,但在其他时候,我想将其他内容添加到我使用 artisan 生成的模型和迁移中。这可以做到吗?我需要重新编译工匠二进制文件吗?

【问题讨论】:

  • 很酷的问题,这些东西实际上可以通过简单地将它们添加到配置和发布来定制。

标签: php laravel laravel-artisan


【解决方案1】:

这有点棘手,但如果你知道如何在容器周围找到自己的路,你应该没问题。

首先,您必须通过扩展默认值来覆盖ArtisanServiceProvider 并更改此方法。

/**
 * Register the command.
 *
 * @return void
 */
protected function registerControllerMakeCommand()
{
    $this->app->singleton('command.controller.make', function ($app) {
        return new ControllerMakeCommand($app['files']);
    });
}

通过这样做,您只需允许自己在容器中分配一个自定义 ControllerMakeCommand

然后您只需复制该类并更改您想要的代码。

在你的情况下是存根文件。

/**
 * Get the stub file for the generator.
 *
 * @return string
 */
protected function getStub()
{
    $stub = null;

    if ($this->option('parent')) {
        $stub = '/stubs/controller.nested.stub';
    } elseif ($this->option('model')) {
        $stub = '/stubs/controller.model.stub';
    } elseif ($this->option('invokable')) {
        $stub = '/stubs/controller.invokable.stub';
    } elseif ($this->option('resource')) {
        $stub = '/stubs/controller.stub';
    }

    if ($this->option('api') && is_null($stub)) {
        $stub = '/stubs/controller.api.stub';
    } elseif ($this->option('api') && ! is_null($stub) && ! $this->option('invokable')) {
        $stub = str_replace('.stub', '.api.stub', $stub);
    }

    $stub = $stub ?? '/stubs/controller.plain.stub';

    return __DIR__.$stub;
}

当然,您必须复制存根文件并根据需要对其进行编辑。

【讨论】:

  • 我找不到ArtisanServiceProvider 文件,有什么线索吗?
  • 你是对的,我刚刚注意到它是通过ConsoleSupportServiceProvider注册的,所以你也需要覆盖它。你可以在config/app.php找到它。
猜你喜欢
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 2014-01-27
  • 2017-08-28
  • 2013-09-22
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
相关资源
最近更新 更多