Создать несколько файлов с помощью команды laravel - PullRequest
1 голос
/ 11 февраля 2020

не могли бы вы помочь мне с проблемой, которая у меня есть? Я создал команду с php artisan make:command для генерации классов типов репозитория из существующих моделей. Проблема в том, что мне нужно, чтобы вместо создания одного файла из заглушки, мне нужно было создать 2 или более файлов. Я не могу найти документацию по этому вопросу. В настоящее время я достиг только того, что я генерирую только один файл из шаблона.

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputArgument;

class MakeRepository extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:repository';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new repository';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Repository';

    /**
     * @inheritDoc
     */
    protected function getStub()
    {
        return __DIR__ . '/stubs/MakeRepository/ModelRepositoryInterface.stub';
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'The name of the model to which the repository will be generated'],
        ];
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Repositories';
    }
}

EDIT # 1

У меня есть 2 файла-заглушки внутри каталога:

app/Console/Commands/stubs/MakeRepository

ModelRepository.stub
ModelRepositoryInterface.stub

Я хочу, чтобы при выполнении команды ... ex: php artisan make:repository Blog эти 2 файла создавались в следующем каталоге:

/app/Repositories/Blog/BlogRepository.php
/app/Repositories/Blog/BlogRepositoryInterface.php

Ответы [ 2 ]

3 голосов
/ 11 февраля 2020

вы можете использовать glob, чтобы получить ваши заглушки в массиве, затем l oop поверх них, чтобы создать несколько файлов

foreach(glob(stubs_path('stubs/Repository/*.stub') as $stub){
            copy(stubs_path('stubs/Repository/'.$stub), $repositoryLocation . 'Repository.php');
}
1 голос
/ 11 февраля 2020

Вы можете написать новую команду для создания интерфейса репозитория, а затем вызвать ее в MakeRepository.

Я думаю, что этот метод соответствует SRP.

// In MakeRepository.php

// Override handle method
public function handle()
{
    if (parent::handle() === false && ! $this->option('force')) {
        return false;
    }

    if ($this->option('interface')) {
        $this->call('make:repository-interface', ['name' => $this->getNameInput() . 'Interface']);

    }
}

/**
 * Get the console command arguments.
 *
 * @return array
 */
protected function getArguments()
{
    return [
        ['name', InputArgument::REQUIRED, 'The name of the model to which the repository will be generated'],
        ['interface', 'i', InputOption::VALUE_NONE, 'Create a new interface for the repository'],
    ];
}

Вы также можете обратиться к коду марки делают официальную. https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Console/ModelMakeCommand.php

...