MVCS 구조로 전환하며 수동으로 파일을 생성하기보다는 Command를 추가하는 것이 나을 것으로 판단함
// app/Traits/CreateArtisanTrait.php
<?php
namespace App\\Traits;
/**
* $this->files 은 부모 Class에서 Filesystem을 받아야 함.
*
* Trait CreateArtisanTrait
* @package App\\Traits
*/
trait CreateArtisanTrait
{
/**
* 생성할 수 있는 디렉토리명
*
* @var string[]
*/
private $directoryAllowed = ['Services', 'Traits'];
/**
* @var string
*/
private $sampleClassPrefix = 'Sample';
/**
* @var
*/
private $suffix;
/**
* @var
*/
private $directory;
/**
* @var
*/
private $fileName;
/**
* @param string $directory
* @param string $fileName
* @return bool
*/
public function create(string $directory, string $fileName)
{
if (empty($fileName)) {
$this->error('만드실 파일명을 입력해 주세요.');
return false;
}
if (empty($directory)) {
$this->error('만드실 디렉토리를 입력해 주세요.');
return false;
}
$this->directory = ucfirst($directory);
$this->fileName = $fileName;
$this->suffix = substr($this->directory, 0, -1);
$this->createFile();
}
/**
* @return bool
*/
private function createFile()
{
$makeFile = app_path($this->directory . '/' . $this->fileName . '.php');
if ($this->files->exists($makeFile)) {
$this->error('해당 파일은 이미 존재합니다.');
return false;
}
// SampleTrait, SampleService 등의 클래스들의 클래스명을 찾아 파일명으로 변경시켜 준다.
$sampleClass = str_replace($this->sampleClassPrefix . $this->suffix, $this->fileName, $this->getSampleClass());
$this->files->put($makeFile, $sampleClass);
$this->info($this->directory . ' 생성 성공');
return true;
}
/**
* @return mixed
*/
private function getSampleClass()
{
return $this->files->get(
app_path($this->directory . '/' . $this->sampleClassPrefix . $this->suffix . '.php')
);
}
}
// app/Services/SampleService.php
<?php
namespace App\\Services;
class SampleService
{
public function index()
{
//
}
}
// app/Console/Commands/CreateService.php
<?php
namespace App\\Console\\Commands;
use App\\Traits\\CreateArtisanTrait;
use Illuminate\\Console\\Command;
use Illuminate\\Filesystem\\Filesystem;
/**
* Class CreateService
* @package App\\Console\\Commands
*/
class CreateService extends Command
{
use CreateArtisanTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:service {name}'; // {name}은 console에서 넘겨 받은 서비스명
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new SampleService Class';
/**
* @var \\App\\Console\\Commands\\Filesystem
*/
public $files;
/**
* Create a new command instance.
*
* @param \\Illuminate\\Filesystem\\Filesystem $files
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$name = trim($this->argument('name'));
$this->create('Services', $name);
}
}
php artisan make:service UserService