artisan 은 라라벨에 포함되어 있는 커맨드 라인 유틸리티로 라라벨 개발을 도와 주는 명령어의 모음입니다.
make:console
artisan 의 make 명령어중 console 로 artisan 에 새로운 명령을 추가할 수 있습니다.
$ php artisan make:console FooBars --command=foo:bar
BASH
--command=foo:bar 는 php artisan foo:bar 로 추가된 명령어를 실행할 수 있게 합니다.
Command class는 app/Console/Commands/FooBars.php 로 존재합니다.
Console Kernel 에 추가
아직은 artisan list 명령어를 실행해도 추가된 명령이 보이지 않을 것입니다.
app/Console/Kernel.php 에 추가된 클래스를 수동으로 등록해 주어야 artisan 에서 인식할 수 있습니다.
app/Console/Kernel.php
protected $commands = [
\App\Console\Commands\Inspire::class,
\App\Console\Commands\FooBars::class,
];
PHP
$ php artisan list | grep foofoo
foo:bar Command description.
BASH
기능 구현
실행할 동작은 Commands 의 handle () 메소드에 추가하면 됩니다.
app/Console/Commands/FooBars.php
public function handle()
{
//
$this->info('Name: ');
}
PHP
$ php artisan foo:bar
Name:
CODE
argument 처리
명령어 실행시 아규먼트를 받아서 더욱 유연하게 만들고 싶을 수 있습니다. 라라벨 5.1 부터 command signature 기능이 개선되어 손쉽게 처리할 수 있습니다.
받아들일 아규먼트는 $signature 변수에 {var} 형식으로 기술하면 되며 handle() 에서 $this->argument('var') 와 같이 전달된 아규먼트에 접근할 수 있습니다.
다음은 name 이라는 아규먼트를 받는 Command 예제입니다.
protected $signature = 'foo:bar {name}';
public function handle()
{
//
$this->info('Name:' . $this->argument('name'));
}
BASH
$ php artisan foo:bar lesstif
Name: lesstif
BASH
아규먼트가 없을 경우 다음과 같이 RuntimeException 예외가 발생합니다.
$ php artisan foo:bar
[RuntimeException]
Not enough arguments.
BASH
이 문제는 아규먼트를 생략 가능(? 추가)하게 하거나 아규먼트에 기본 값을 설정하면 됩니다.
아규먼트 생략 가능
protected $signature = 'foo:bar {name?}';
PHP
아규먼트 기본 값 설정
protected $signature = 'foo:bar {name=lesstif}';
PHP
옵션 처리
아규먼트대신 -- 를 이용하여 옵션으로 처리하고 싶을 경우도 $signature 에 수정하면 되며 대신 옵션 앞에 -– 를 추가하면 됩니다.
전달된 옵션은 $this->option() 메소드로 접근할 수 있습니다.
app/Console/Commands/FooBars.php
protected $signature = 'foo:bar {name=lesstif} {--level=1}';
public function handle()
{
$this->info('name:' . $this->argument('name') .
' Level:' . $this->option('level'));
}
PHP
$ php artisan foo:bar --level=5
name:lesstif Level:5
$ php artisan foo:bar
name:lesstif Level:1
BASH
Ref