Laravel Command Sistemi
3 min readNov 5, 2024
Laravel Command sistemini detaylıca inceleyelim:
1. Command Nedir?
- Artisan CLI (Command Line Interface) üzerinden çalıştırılabilen komutlardır
- Tekrar eden işlemleri otomatize etmek için kullanılır
- Scheduled Tasks (zamanlanmış görevler) için temel oluşturur
2. Ne Zaman Kullanılır?
Örnek senaryolar:
- Database bakım işlemleri
- Cache temizleme
- Email gönderme işlemleri
- Dosya sistemi işlemleri
- Veri import/export işlemleri
- Cron jobs
- Sistem bakım işlemleri
3. Command Oluşturma ve Yapısı:
a) Command Oluşturma:
# Temel command oluşturma
php artisan make:command SendEmails
# Scheduled command oluşturma
php artisan make:command SendEmails --command=emails:send
b) Temel Command Yapısı:
class SendEmails extends Command
{
// Command'in signature'ı (imzası)
protected $signature = 'emails:send {user} {--queue=}';
// Command açıklaması
protected $description = 'Send emails to a user';
public function handle()
{
// Command mantığı burada
$user = User::find($this->argument('user'));
$queue = $this->option('queue');
// İşlem başarılı mesajı
$this->info('Emails sent successfully!');
}
}
4. Command Signature Yapısı:
a) Argümanlar:
// Zorunlu argüman
protected $signature = 'email:send {user}';
// Opsiyonel argüman
protected $signature = 'email:send {user?}';
// Varsayılan değerli argüman
protected $signature = 'email:send {user=1}';
// Array argüman
protected $signature = 'email:send {user*}';
b) Seçenekler (Options):
// Boolean seçenek
protected $signature = 'email:send {--queue}';
// Değer alan seçenek
protected $signature = 'email:send {--queue=}';
// Varsayılan değerli seçenek
protected $signature = 'email:send {--queue=default}';
// Kısaltmalı seçenek
protected $signature = 'email:send {--Q|queue}';
5. Command Input ve Output:
a) Input Alma:
public function handle()
{
// Argüman alma
$userId = $this->argument('user');
$allArgs = $this->arguments();
// Seçenek alma
$queue = $this->option('queue');
$allOpts = $this->options();
// Kullanıcıdan input alma
$name = $this->ask('What is your name?');
$password = $this->secret('What is the password?');
// Onay alma
if ($this->confirm('Do you wish to continue?')) {
//
}
// Seçenek sunma
$drink = $this->choice(
'Select drink',
['coffee', 'tea', 'water'],
'coffee'
);
}
b) Output Gösterme:
public function handle()
{
// Bilgi mesajı
$this->info('Display this on the screen');
// Hata mesajı
$this->error('Something went wrong!');
// Uyarı mesajı
$this->warn('This is a warning');
// Başarı mesajı
$this->line('Display this uncolored message');
// Tablo gösterme
$this->table(
['Name', 'Email'],
User::all(['name', 'email'])->toArray()
);
// Progress bar
$bar = $this->output->createProgressBar(count($users));
foreach ($users as $user) {
$this->processUser($user);
$bar->advance();
}
$bar->finish();
}
6. Pratik Command Örnekleri:
a) Veri Temizleme Komutu:
class CleanupOldData extends Command
{
protected $signature = 'cleanup:old-data
{days=30 : Number of days to keep}
{--dry-run : Run without deleting}';
protected $description = 'Clean up old records from the database';
public function handle()
{
$days = $this->argument('days');
$isDryRun = $this->option('dry-run');
$query = DB::table('logs')
->where('created_at', '<', now()->subDays($days));
$count = $query->count();
if ($isDryRun) {
$this->info("Would delete $count records");
return;
}
$query->delete();
$this->info("Deleted $count records");
}
}
b) Veri Import Komutu:
class ImportUsers extends Command
{
protected $signature = 'import:users
{file : The CSV file path}
{--chunk=1000 : Chunk size for processing}';
public function handle()
{
$file = $this->argument('file');
$chunk = $this->option('chunk');
if (!file_exists($file)) {
$this->error("File not found: $file");
return 1;
}
$bar = $this->output->createProgressBar(count(file($file)));
Excel::import(new UsersImport($bar), $file);
$bar->finish();
$this->newLine();
$this->info('Import completed successfully!');
}
}
7. Command Scheduling:
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
// Her gün gece yarısı çalış
$schedule->command('cleanup:old-data')
->daily();
// Her saatte bir çalış
$schedule->command('emails:send')
->hourly()
->withoutOverlapping()
->emailOutputTo('admin@example.com');
// Özel cron zamanlaması
$schedule->command('backup:run')
->cron('0 * * * *')
->environments(['production']);
}
8. Command’larda Queue Kullanımı:
class ProcessPodcasts extends Command
{
protected $signature = 'podcasts:process';
public function handle()
{
$podcasts = Podcast::all();
$bar = $this->output->createProgressBar(count($podcasts));
foreach ($podcasts as $podcast) {
ProcessPodcast::dispatch($podcast);
$bar->advance();
}
$bar->finish();
}
}
9. Testing:
class CommandTest extends TestCase
{
public function test_cleanup_command()
{
// Test verisi oluştur
Log::factory()->count(50)->create([
'created_at' => now()->subDays(40)
]);
// Komutu çalıştır
$this->artisan('cleanup:old-data')
->expectsQuestion('Are you sure?', 'yes')
->assertExitCode(0);
// Sonucu kontrol et
$this->assertDatabaseCount('logs', 0);
}
}
10. Best Practices:
Error Handling:
public function handle()
{
try {
// Command mantığı
return 0; // Başarılı
} catch (Exception $e) {
$this->error($e->getMessage());
return 1; // Hata
}
}
Validation:
public function handle()
{
$file = $this->argument('file');
if (!file_exists($file)) {
$this->error('File does not exist!');
return 1;
}
if (!$this->validate()) {
return 1;
}
}
private function validate()
{
// Validation mantığı
}
Dependency Injection:
class SendEmails extends Command
{
protected $mailer;
public function __construct(Mailer $mailer)
{
parent::__construct();
$this->mailer = $mailer;
}
}