Команди Artisan на основі closures у Laravel підтримують повну ін'єкцію залежностей, що дає змогу впроваджувати сервіси безпосередньо в параметри команд разом із традиційними аргументами та опціями.
Контейнер сервісів автоматично розв'язує залежності, якщо ви вказуєте їх у параметрах closures:
use App\Services\EmailService;
Artisan::command('email:digest {recipient}', function (EmailService $emailer, string $recipient) {
$emailer->sendDigest($recipient);
});
Ця функція поєднує зручність інлайн-команд із потужною системою розв'язання залежностей Laravel.
use App\Services\ReportGenerator;
use App\Services\FileUploader;
use App\Models\Customer;
Artisan::command('reports:generate {customer_id} {--format=pdf}', function (
ReportGenerator $generator,
FileUploader $uploader,
string $customer_id
) {
$customer = Customer::findOrFail($customer_id);
$format = $this->option('format');
$this->info("Генерація звіту у форматі {$format} для {$customer->name}");
$reportData = $generator->createCustomerReport($customer, $format);
$filename = "customer-{$customer_id}-report." . $format;
$uploadPath = $uploader->store($reportData, 'reports/' . $filename);
$this->info("Звіт успішно згенеровано");
$this->line("Розташування файлу: {$uploadPath}");
if ($this->confirm('Відправити звіт електронною поштою?')) {
$customer->notify(new ReportGeneratedNotification($uploadPath));
$this->info("Сповіщення надіслано");
}
});
Artisan::command('cleanup:temp-files {--days=7}', function (
FilesystemManager $filesystem,
CacheManager $cache
) {
$days = (int) $this->option('days');
$cutoffDate = now()->subDays($days);
$this->info("Очищення файлів старше {$days} днів");
$tempPath = storage_path('app/temp');
$files = $filesystem->disk('local')->allFiles('temp');
$deletedCount = 0;
foreach ($files as $file) {
$lastModified = $filesystem->disk('local')->lastModified($file);
if ($lastModified < $cutoffDate->timestamp) {
$filesystem->disk('local')->delete($file);
$deletedCount++;
}
}
$cache->tags(['temp-files'])->flush();
$this->info("Очищення завершено: видалено {$deletedCount} файлів");
});
Ін'єкція залежностей у командних closures дозволяє швидко презентувати ідеї, зберігаючи чисту архітектуру та тестованість ваших командних утиліт.