Skip to Content

Terrain 2 — Console & commandes

🔍 Renfort : 4.6.

1. Première commande ⭐

🕹️ Mission : générez une commande app:hello qui affiche un success.

✅ Solution

php bin/console make:command app:hello, puis dans execute() : $io = new SymfonyStyle($input, $output); $io->success('Bonjour !'); return Command::SUCCESS;

2. Argument requis ⭐

🕹️ Mission : ajoutez un argument name requis et affichez « Bonjour {name} ».

✅ Solution

$this->addArgument('name', InputArgument::REQUIRED, 'Nom'); // execute : $io->text('Bonjour ' . $input->getArgument('name'));

3. Option --dry-run ⭐⭐

🕹️ Mission : ajoutez une option booléenne --dry-run et affichez un note si activée.

✅ Solution

$this->addOption('dry-run', null, InputOption::VALUE_NONE, 'Simuler'); if ($input->getOption('dry-run')) $io->note('Mode simulation.');

4. Injection de service ⭐⭐

🕹️ Mission : injectez un BookingRepository dans la commande et affichez le nombre de réservations.

✅ Solution

public function __construct(private BookingRepository $repo) { parent::__construct(); } // execute : $io->text('Réservations : ' . $this->repo->count([]));

5. Tableau de sortie ⭐⭐

🕹️ Mission : affichez les 5 dernières réservations dans un tableau (id, email, statut).

✅ Solution

$rows = array_map(fn($b) => [$b->getId(), $b->getCustomerEmail(), $b->getStatus()->value], $this->repo->findBy([], ['id' => 'DESC'], 5)); $io->table(['ID', 'Email', 'Statut'], $rows);

6. Barre de progression ⭐⭐⭐

🕹️ Mission : traitez 1000 éléments avec une barre de progression.

✅ Solution

$io->progressStart(1000); foreach ($items as $i) { /* ... */ $io->progressAdvance(); } $io->progressFinish();

7. Import par lots ⭐⭐⭐⭐

🕹️ Mission : importez un CSV en flushant + clear() tous les 100.

✅ Solution

foreach (readLines($file) as $i => $line) { $em->persist($this->toEntity($line)); if ($i % 100 === 0) { $em->flush(); $em->clear(); } } $em->flush();

8. Commande planifiée ⭐⭐⭐⭐

🕹️ Mission : faites déclencher un message SendDailyReminders chaque jour à 8h via le Scheduler. 🔍 12.3.

✅ Solution

#[AsSchedule] final class MainSchedule implements ScheduleProviderInterface { public function getSchedule(): Schedule { return (new Schedule())->add(RecurringMessage::cron('0 8 * * *', new SendDailyReminders())); } }

Terrain suivant : Routing & contrôleurs.