> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Tutorial - Laravel Console Starter

> Passi per costruire un'app console con Laravel Console Starter. Impari a creare comandi, schedulare con GitHub Actions, inviare notifiche e vedi esempi pratici.

## Introduzione

In questo tutorial costruirai un'applicazione Laravel con comandi Artisan personalizzati usando `revolution/laravel-console-starter`.

I vantaggi di usare questo starter kit:

* **Setup rapido** — puoi iniziare subito lo sviluppo di app console senza configurazioni complesse
* **Ecosistema Laravel** — puoi usare le funzionalità di Laravel come task scheduling, database e notifiche
* **Comandi Artisan** — con il potente sistema Artisan di Laravel puoi creare e gestire facilmente i tuoi comandi
* **Facilità di test** — puoi scrivere test per i comandi con il framework di testing di Laravel

## Prerequisiti

Installa il seguente software.

* PHP `^8.3`
* Composer ([https://getcomposer.org/](https://getcomposer.org/))
* Laravel Installer (`composer global require laravel/installer`)

## Setup del progetto

<Steps>
  <Step title="Crea un nuovo progetto">
    Esegui il seguente comando nel terminale.

    ```bash theme={null}
    laravel new my-app --using=revolution/laravel-console-starter --no-interaction
    ```

    Viene creata la directory `my-app` e configurata la struttura base dell'app console.

    All'installazione vengono eseguite automaticamente le seguenti operazioni.

    * Generazione del file `.env` a partire da `.env.example`
    * Impostazione dell'application key con `php artisan key:generate`

    Struttura principale delle directory:

    ```
    my-app/
    ├── app/Console/Commands/   # I comandi personalizzati
    ├── .github/workflows/
    │   └── cron.yml            # Esempio di schedulazione GitHub Actions
    ├── config/                 # Configurazione dell'applicazione
    └── routes/console.php      # Registrazione dei comandi
    ```
  </Step>

  <Step title="Verifica la configurazione dell'ambiente">
    Per impostazione predefinita, l'invio email è impostato sul log (`MAIL_MAILER=log`).

    Se ti serve un vero invio di email, configura nel file `.env` servizi come Mailgun, Postmark o SES.
  </Step>
</Steps>

## Creazione di un comando console

<Steps>
  <Step title="Genera un comando">
    Crea un nuovo comando con `make:command` di Artisan.

    ```bash theme={null}
    php artisan make:command YourCommandName --command=your:command
    ```

    * `YourCommandName` — nome della classe del comando da creare (es.: `SendDailyReport`)
    * `your:command` — nome invocabile del comando (es.: `report:send-daily`)

    Viene generato `app/Console/Commands/YourCommandName.php`.
  </Step>

  <Step title="Implementa il comando">
    Modifica il file generato per implementare la logica. Ecco un esempio "Hello World".

    ```php theme={null}
    <?php

    namespace App\Console\Commands;

    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Log;

    class HelloWorldCommand extends Command
    {
        protected $signature = 'hello:world';
        protected $description = 'Displays a hello world message in the log';

        public function handle(): int
        {
            Log::info('Hello, World from Artisan Command!');
            $this->info('Hello, World message has been logged.');
            return Command::SUCCESS;
        }
    }
    ```

    In `$signature` definisci il nome invocabile del comando e scrivi la logica nel metodo `handle()`.
  </Step>

  <Step title="Esegui il comando">
    ```bash theme={null}
    php artisan hello:world
    ```

    Dopo l'esecuzione, il messaggio viene stampato in `storage/logs/laravel.log` e in console.
  </Step>
</Steps>

## Task scheduling con GitHub Actions

Usando GitHub Actions puoi eseguire comandi in modo periodico senza bisogno di cron sul server.

<Steps>
  <Step title="Controlla il file workflow">
    Lo starter kit include `.github/workflows/cron.yml` già preconfigurato.

    ```yaml theme={null}
    name: cron

    on:
      schedule:
        - cron: '0 0 * * *'  # Ogni giorno a mezzanotte UTC

    jobs:
      cron:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - uses: shivammathur/setup-php@v2
            with:
              php-version: 8.5
              coverage: none
          - run: composer install --no-dev -q
          - run: cp .env.example .env
          - run: php artisan key:generate
          - run: php artisan inspire
    ```
  </Step>

  <Step title="Cambia il comando">
    Sostituisci `php artisan inspire` con il tuo comando.

    ```yaml theme={null}
    - name: Run Command
      run: php artisan your:command
    ```

    Per eseguire più comandi:

    ```yaml theme={null}
    - name: Run Commands
      run: |
        php artisan first:command
        php artisan second:command
    ```
  </Step>

  <Step title="Regola la pianificazione">
    Modifica l'espressione `cron` per impostare la frequenza.

    | Espressione cron | Quando                     |
    | ---------------- | -------------------------- |
    | `0 0 * * *`      | Ogni giorno alle 00:00 UTC |
    | `0 */6 * * *`    | Ogni 6 ore                 |
    | `0 0 * * 1`      | Ogni lunedì a mezzanotte   |
  </Step>

  <Step title="Gestisci le informazioni sensibili come secret">
    Le informazioni sensibili come API key e password vanno tenute nei secret della repository GitHub.

    Aggiungi i secret in **Settings > Secrets and variables > Actions** della repository GitHub e referenziali nel workflow.

    ```yaml theme={null}
    - name: Run Command with Secrets
      run: php artisan your:command
      env:
        API_KEY: ${{ secrets.API_KEY }}
        DB_PASSWORD: ${{ secrets.DATABASE_PASSWORD }}
    ```
  </Step>
</Steps>

## Notifiche

Puoi notificare via email, Slack, ecc. il risultato o gli errori di un comando.

<Steps>
  <Step title="Crea una classe di notifica">
    ```bash theme={null}
    php artisan make:notification TaskCompleted
    ```

    Viene generato `app/Notifications/TaskCompleted.php`.
  </Step>

  <Step title="Configura il canale di notifica">
    Se necessario, pubblica i file di configurazione.

    ```bash theme={null}
    php artisan config:publish mail
    php artisan config:publish services
    ```
  </Step>

  <Step title="Invia la notifica dal comando">
    ```php theme={null}
    <?php

    namespace App\Console\Commands;

    use App\Notifications\TaskCompleted;
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Notification;

    class ProcessDataCommand extends Command
    {
        protected $signature = 'data:process';
        protected $description = 'Elabora i dati e invia una notifica al completamento';

        public function handle()
        {
            $this->info('Elaborazione dei dati in corso...');

            // Logica di elaborazione...

            Notification::route('mail', 'admin@example.com')
                ->notify(new TaskCompleted('Elaborazione dei dati completata con successo'));

            return Command::SUCCESS;
        }
    }
    ```
  </Step>
</Steps>

<Info>
  Per i dettagli consulta la [documentazione delle notifiche di Laravel](https://laravel.com/docs/notifications).
</Info>

## Esempi pratici di applicazioni

### Esempio 1: monitoraggio uptime di siti web e alert Slack

Un comando che verifica se un sito è online e invia un alert su Slack in caso di problemi.

<Steps>
  <Step title="Installa il canale di notifica Slack">
    ```bash theme={null}
    composer require laravel/slack-notification-channel
    ```
  </Step>

  <Step title="Crea comando e notifica">
    ```bash theme={null}
    php artisan make:command MonitorWebsites --command=monitor:websites
    php artisan make:notification WebsiteDown
    ```
  </Step>

  <Step title="Configura Slack">
    ```bash theme={null}
    php artisan config:publish services
    ```

    Aggiungi l'URL del webhook Slack in `.env`.

    ```
    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL
    ```

    Aggiorna `config/services.php`.

    ```php theme={null}
    'slack' => [
        'webhook_url' => env('SLACK_WEBHOOK_URL'),
    ],
    ```
  </Step>

  <Step title="Implementa la notifica">
    Modifica `app/Notifications/WebsiteDown.php`.

    ```php theme={null}
    <?php

    namespace App\Notifications;

    use Illuminate\Notifications\Messages\SlackMessage;
    use Illuminate\Notifications\Notification;

    class WebsiteDown extends Notification
    {
        public function __construct(
            protected string $website,
            protected string $error,
        ) {}

        public function via($notifiable): array
        {
            return ['slack'];
        }

        public function toSlack($notifiable): SlackMessage
        {
            return (new SlackMessage)
                ->error()
                ->content('Alert sito down!')
                ->attachment(function ($attachment) {
                    $attachment->title($this->website)
                               ->content("Errore: {$this->error}")
                               ->timestamp(now());
                });
        }
    }
    ```
  </Step>

  <Step title="Implementa il comando">
    Modifica `app/Console/Commands/MonitorWebsites.php`.

    ```php theme={null}
    <?php

    namespace App\Console\Commands;

    use App\Notifications\WebsiteDown;
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Http;
    use Illuminate\Support\Facades\Log;
    use Illuminate\Support\Facades\Notification;

    class MonitorWebsites extends Command
    {
        protected $signature = 'monitor:websites {--timeout=10}';
        protected $description = 'Verifica uptime dei siti e invio di alert Slack in caso di down';

        protected array $websites = [
            'https://example.com',
            'https://yourwebsite.com',
        ];

        public function handle(): int
        {
            $timeout = (int) $this->option('timeout');
            $webhookUrl = config('services.slack.webhook_url');
            $hasErrors = false;

            foreach ($this->websites as $website) {
                try {
                    $response = Http::timeout($timeout)->get($website);
                    if ($response->successful()) {
                        $this->info("{$website}: online ✓");
                    } else {
                        $error = "Stato HTTP: " . $response->status();
                        $this->error("{$website}: down ({$error})");
                        Notification::route('slack', $webhookUrl)
                            ->notify(new WebsiteDown($website, $error));
                        $hasErrors = true;
                    }
                } catch (\Exception $e) {
                    $this->error("{$website}: errore ({$e->getMessage()})");
                    Log::error("Verifica di {$website} fallita", ['error' => $e->getMessage()]);
                    Notification::route('slack', $webhookUrl)
                        ->notify(new WebsiteDown($website, $e->getMessage()));
                    $hasErrors = true;
                }
            }

            return $hasErrors ? Command::FAILURE : Command::SUCCESS;
        }
    }
    ```
  </Step>

  <Step title="Schedula con GitHub Actions">
    Aggiorna `.github/workflows/cron.yml`.

    ```yaml theme={null}
    name: Website Monitoring

    on:
      schedule:
        - cron: '*/15 * * * *'  # Ogni 15 minuti

    jobs:
      monitor:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - uses: shivammathur/setup-php@v2
            with:
              php-version: 8.5
          - run: composer install --no-dev -q
          - run: cp .env.example .env
          - run: php artisan key:generate
          - name: Monitor Websites
            run: php artisan monitor:websites
            env:
              SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
    ```
  </Step>
</Steps>

### Esempio 2: aggiornamento portafoglio crypto e notifica Discord

Un comando che recupera i prezzi delle crypto dall'API CoinGecko e invia gli aggiornamenti tramite webhook Discord.

<Steps>
  <Step title="Installa il canale di notifica Discord">
    ```bash theme={null}
    composer require revolution/laravel-notification-discord-webhook
    ```
  </Step>

  <Step title="Crea comando e notifica">
    ```bash theme={null}
    php artisan make:command UpdateCryptoPortfolio --command=crypto:portfolio
    php artisan make:notification CryptoPortfolioUpdate
    ```
  </Step>

  <Step title="Configura Discord">
    Aggiungi l'URL del webhook Discord in `.env`.

    ```
    DISCORD_WEBHOOK=https://discord.com/api/webhooks/YOUR/WEBHOOK
    ```

    Aggiorna `config/services.php`.

    ```php theme={null}
    'discord' => [
        'webhook' => env('DISCORD_WEBHOOK'),
    ],
    ```
  </Step>

  <Step title="Implementa ed esegui il comando">
    Per l'implementazione dettagliata consulta il [tutorial nella repository GitHub](https://github.com/invokable/laravel-console-starter/blob/main/docs/tutorial_ja.md).

    ```bash theme={null}
    php artisan crypto:portfolio
    ```
  </Step>
</Steps>

### Esempio 3: scraping di contenuti dal web e notifica via email

Un comando che effettua scraping di contenuti da un sito e invia i risultati via email.

<Steps>
  <Step title="Crea comando e notifica">
    ```bash theme={null}
    php artisan make:command WebScraper --command=scrape:website
    php artisan make:notification ScrapingCompleted
    ```
  </Step>

  <Step title="Configura la mail">
    ```bash theme={null}
    php artisan config:publish mail
    ```

    Aggiungi la configurazione della mail nel file `.env`.

    ```
    MAIL_MAILER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=your_username
    MAIL_PASSWORD=your_password
    MAIL_ENCRYPTION=tls
    MAIL_FROM_ADDRESS=your-app@example.com
    MAIL_FROM_NAME="${APP_NAME}"
    ```
  </Step>

  <Step title="Implementa ed esegui il comando">
    ```php theme={null}
    protected $signature = 'scrape:website {--url=https://example.com} {--email=admin@example.com}';

    public function handle(): int
    {
        $url = $this->option('url');
        $email = $this->option('email');

        $response = Http::timeout(30)->get($url);

        // Elabora il contenuto e invia la notifica...
        Notification::route('mail', $email)
            ->notify(new ScrapingCompleted(true, $url, $title, $content));

        return Command::SUCCESS;
    }
    ```

    ```bash theme={null}
    php artisan scrape:website --email=admin@example.com
    ```
  </Step>
</Steps>

## Passi successivi

Ora conosci le basi per costruire un'applicazione console Laravel con `revolution/laravel-console-starter`.

Per approfondire:

* **Esplora la documentazione Laravel** — verifica sulla [documentazione ufficiale Laravel](https://laravel.com/docs) le funzionalità che possono potenziare la tua app console
* **Aggiungi test** — scrivi test per i comandi con il framework di testing di Laravel per garantirne l'affidabilità
* **Valuta lo sviluppo di pacchetti** — se crei comandi simili in più progetti, valuta di pubblicarli come pacchetto Laravel riutilizzabile
* **Segui le novità** — segui [Laravel News](https://laravel-news.com/) e il blog ufficiale per restare aggiornato sulle best practice


## Related topics

- [Laravel Console Starter](/it/packages/laravel-console-starter/index.md)
- [Starter kit](/it/starter-kits.md)
- [Come creare uno starter kit per Laravel](/it/advanced/starter-kit-creation.md)
- [Test da console](/it/console-tests.md)
- [Tutorial per bot - Laravel Bluesky](/it/packages/laravel-bluesky/bot-tutorial.md)
