배움/PHP
Laravel Command 기능
spaces25
2025. 4. 11. 13:40
반응형
Laravel에서 Command 기능은 Artisan 콘솔 명령어를 생성하고 실행할 수 있게 해주는 기능. Artisan은 Laravel의 강력한 CLI(Command Line Interface) 도구로, 커맨드를 만들어 개발 프로세스를 자동화하거나 반복 작업을 간편하게 수행할 수 있게 도와줌.
✅ Laravel Command 기본 개념
Laravel에서는 커맨드를 php artisan make:command 명령어로 생성해요. 생성된 커맨드는 app/Console/Commands 디렉터리에 저장되며, Artisan을 통해 실행할 수 있음.
📦 Command 생성 방법
php artisan make:command CustomCommandName
예)
php artisan make:command SendEmails
🧱 Command 구조
생성된 파일 예시 (app/Console/Commands/SendEmails.php):
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SendEmails extends Command
{
// Artisan 명령어 이름
protected $signature = 'emails:send';
// 설명 (php artisan list에서 보임)
protected $description = 'Send emails to users';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// 실제 로직
$this->info('Sending emails...');
// 예: Mail::to($user)->send(new Notification());
}
}
🏃 실행 방법
php artisan emails:send
✍️ 옵션 & 인자 사용하기
protected $signature = 'emails:send {userId} {--queue}';
public function handle()
{
$userId = $this->argument('userId');
$queue = $this->option('queue');
$this->info("Sending email to user $userId, queue: " . ($queue ? 'yes' : 'no'));
}
🔄 스케줄링과 연동 (선택사항)
app/Console/Kernel.php에서 커맨드를 자동으로 주기적으로 실행할 수도 있어요.
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:send')->daily();
}
✨ 요약
요소설명
php artisan make:command | 커맨드 생성 |
$signature | 명령어 이름 및 옵션 정의 |
handle() | 실행 로직 |
php artisan your:command | 실행 방법 |
Kernel에 등록 | 스케줄링 가능 |
반응형