박유성의 라라벨 블로그

artisan command를 활용한 Service 추가하기 본문

Tip

artisan command를 활용한 Service 추가하기

Matt.park 2020. 7. 17. 10:23

artisan 를 활용하면 Controller 혹은 Model 을 쉽게 만들 수 있다.

 

비즈니스 로직 같은 경우는 Service 쪽으로 빼내어 작업하는 경우가 많은데, 매번 새 파일 생성 후 작성하는게 은근히 귀찮다. 이런 번거로움을 줄이기 위해 오늘은 php artisan make:service {서비스명} 을 만들어 주는 작업을 진행할 것이다.

 

 

Trait

Traits 폴더 생성과 함께 CreateArtisanTrait.php 파일을 생성 해 준다.

 

Traits 폴더생성
$ mkdir {라라벨프로젝트명}/app/Traits

 

Trait 생성
// 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')
        );
    }
}

 

 

Service

Services 폴더 생성과 함께 SampleService.php 클래스 파일을 생성 해 준다.

 

Services 폴더 생성
$ mkdir {라라벨프로젝트명}/app/Services

 

서비스 클래스 생성
// app/Services/SampleService.php

<?php


namespace App\Services;

class SampleService
{
    public function __construct()
    {
    }
}

 

이제 미리 준비되어야 할 작업은 끝났다.  artisan 명령어를 활용하여 command 를 추가 시킨다.

$ php artisan make:command CreateService

 

생성된 command는 아래와 같다.

// 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);
    }
}

 

모든 작업이 끝났다. 이제 콘솔에서 artisan 명령어로 service를 생성해 보자.

$ php artisan make:service UserService

'Tip' 카테고리의 다른 글

Laravel + CloudWatch 설정  (0) 2020.09.18
Comments