Создание файла с помощью Artisan Command в Laravel 5.1

Я создал Artisan Command для своего проекта с помощью этой команды:

`php artisan make:console Repositories`

Подпись для указанной выше настраиваемой команды:

protected $signature = 'make:repository {modelName : The name of the model}';

Когда эта команда запускается / запускается, создаются 2 файла:

  1. app/Http/Repositories/Contracts/modelNameRepositoryContract.php
  2. app/Http/Repositories/Eloquent/modelNameRepository.php

Теперь я хочу, чтобы пространство имен, className было записано по умолчанию. То же, что и при стрельбе из make:controller ModelController или make:model Model. В этих файлах записаны необходимые ему вещи по умолчанию. Я хочу только подобное.

Я хочу заполнить файл пространством имен, пространством имен использования и именем класса / контракта по умолчанию. Для этого используется метод handle() из файла Repositories.php:

/**
 * Execute the console command.
 *
 * @return mixed
 */
 public function handle()
 {
     $modelName = $this->argument('modelName');

     if ($modelName === '' || is_null($modelName) || empty($modelName)) {
         $this->error('Model Name Invalid..!');
     }

     if (! file_exists('app/Http/Repositories/Contracts') && ! file_exists('app/Http/Repositories/Eloquent')) {

         mkdir('app/Http/Repositories/Contracts', 0775, true);
         mkdir('app/Http/Repositories/Eloquent', 0775, true);

         $contractFileName = 'app/Http/Repositories/Contracts/' . $modelName . 'RepositoryContract.php';
         $eloquentFileName = 'app/Http/Repositories/Eloquent/' . $modelName . 'Repository.php';

         if(! file_exists($contractFileName) && ! file_exists($eloquentFileName)) {
             $contractFileContent = "<?php\n\nnamespace App\\Http\\Repositories\\Contracts;\n\ninterface " . $modelName . "RepositoryContract\n{\n}";

             file_put_contents($contractFileName, $contractFileContent);

             $eloquentFileContent = "<?php\n\nnamespace App\\Http\\Repositories\\Eloquent;\n\nuse App\\Repositories\\Contracts\\".$modelName."RepositoryContract;\n\nclass " . $modelName . "Repository implements " . $modelName . "RepositoryContract\n{\n}";

             file_put_contents($eloquentFileName, $eloquentFileContent);

             $this->info('Repository Files Created Successfully.');

         } else {
             $this->error('Repository Files Already Exists.');
         }
     }
 }

Я знаю, что описанный выше метод - неправильный способ создания файла с помощью Artisan-команды. Итак, как мне создать файл и заполнить его значениями по умолчанию. Я не мог найти ничего связанного с этим в документации.

Так может ли кто-нибудь мне с этим помочь?

Заранее спасибо.


person Saiyan Prince    schedule 26.09.2015    source источник


Ответы (2)


Я думаю, что лучше всего было бы реализовать существующий генератор Laravel - \ Illuminate \ Console \ GeneratorCommand

Взгляните на \ Illuminate \ Foundation \ Console \ ModelMakeCommand, чтобы увидеть, как это делается. Я уверен, что вы можете создать шаблон и внедрить что-то, что можно заменить на лету.

person Mikhail Kozlov    schedule 26.09.2015

Это код, который я создал, чтобы помочь мне воссоздать файл View Composer с помощью команды Artisan, поскольку эта команда не предоставляется по умолчанию. Возможно, это может вам помочь. Примечание: это для Laravel 8

<?php

namespace viewmodelsimple\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;

class ViewComposer extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'view:composer {composer}';

    protected $files;
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a view composer';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    // public function __construct()
    public function __construct(Filesystem $files)
    {
        $this->files=$files;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $viewComposer=$this->argument('composer');

        if ($viewComposer === '' || is_null($viewComposer) || empty($viewComposer)) {
            return $this->error('Composer Name Invalid..!');
        }

$contents=
'<?php
namespace App\ViewComposers;
    
use Illuminate\View\View;
        
class '.$viewComposer.'
{
        
    /**
    * Create a new '.$viewComposer.' composer.
    *
    * @return void
    */
    public function __construct()
    {
        // Dependencies automatically resolved by service container...
                
    }
        
    /**
    * Bind data to the view.
    *
    * @param  View  $view
    * @return void
    */
    public function compose(View $view)
    {
        //Bind data to view
    }
    
}';
    if ($this->confirm('Do you wish to create '.$viewComposer.' Composer file?')) {
        $file = "${viewComposer}.php";
        $path=app_path();
        
        $file=$path."/ViewComposers/$file";
        $composerDir=$path."/ViewComposers";

        if($this->files->isDirectory($composerDir)){
            if($this->files->isFile($file))
                return $this->error($viewComposer.' File Already exists!');
            
            if(!$this->files->put($file, $contents))
                return $this->error('Something went wrong!');
            $this->info("$viewComposer generated!");
        }
        else{
            $this->files->makeDirectory($composerDir, 0777, true, true);

            if(!$this->files->put($file, $contents))
                return $this->error('Something went wrong!');
            $this->info("$viewComposer generated!");
        }

    }
    }
}
person Abdulhakeem    schedule 17.09.2020