Nessun risultato. Prova con un altro termine.
Guide
Notizie
Software
Tutorial

Installare Laravel WebSockets e Pusher PHP SDK

Installare Laravel WebSockets e Pusher PHP SDK per creare applicazioni Web con supporto alle notifiche in tempo reale
Installare Laravel WebSockets e Pusher PHP SDK per creare applicazioni Web con supporto alle notifiche in tempo reale
Link copiato negli appunti

Giunti a questo punto della nostra guida su Laravel e WebSocket installiamo Laravel WebSockets tramite composer. Da riga di comando digitiamo:

composer require beyondcode/laravel-websockets -w

Dove -w sta per --whit-all-dependiences ed installa tutte le dipendenze del pacchetto. Incluse quelli che potrebbero non essere esplicitamente richieste nel progetto. Verrà registrato automaticamente un fornitore di servizi.

Questo pacchetto include una migrazione per archiviare informazioni statistiche durante l'esecuzione del server WebSocket. Puoi pubblicare il file di migrazione utilizzando il seguente comando:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

Quindi esegui la migrazione:

php artisan migrate

Successivamente devi pubblicare il file di configurazione utilizzando il comando seguente:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

Il file websockets.php

Ottimo! se tutto è andato come previsto dovresti avere un file config/websockets.php con il seguente contenuto:

'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
],
/*
* This package comes with multi tenancy out of the box. Here you can
* configure the different apps that can use the webSockets server.
*
* Optionally you specify capacity so you can limit the maximum
* concurrent connections for a specific app.
*
* Optionally you can disable client events so clients cannot send
* messages to each other via the webSockets.
*/
'apps' => [
[
 'id' => env('PUSHER_APP_ID'),
 'name' => env('APP_NAME'),
 'key' => env('PUSHER_APP_KEY'),
 'secret' => env('PUSHER_APP_SECRET'),
 'path' => env('PUSHER_APP_PATH'),
 'capacity' => null,
 'enable_client_messages' => false,
 'enable_statistics' => true,
 ],
],
/*
* This class is responsible for finding the apps. The default provider
* will use the apps defined in this config file.
*
* You can create a custom provider by implementing the
* `AppProvider` interface.
*/
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,
/*
* This array contains the hosts of which you want to allow incoming requests.
* Leave this empty if you want to accept requests from all hosts.
*/
'allowed_origins' => [
//
],
/*
* The maximum request size in kilobytes that is allowed for an incoming WebSocket request.
*/
'max_request_size_in_kb' => 250,
/*
* This path will be used to register the necessary routes for the package.
*/
'path' => 'laravel-websockets',
/*
* Dashboard Routes Middleware
*
* These middleware will be assigned to every dashboard route, giving you
* the chance to add your own middleware to this list or change any of
* the existing middleware. Or, you can simply stick with this list.
*/
'middleware' => [
'web',
Authorize::class,
],
'statistics' => [
/*
* This model will be used to store the statistics of the WebSocketsServer.
* The only requirement is that the model should extend
* `WebSocketsStatisticsEntry` provided by this package.
*/
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
/**
* The Statistics Logger will, by default, handle the incoming statistics, store them
* and then release them into the database on each interval defined below.
*/
'logger' => BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger::class,
/*
* Here you can specify the interval in seconds at which statistics should be logged.
*/
'interval_in_seconds' => 60,
/*
* When the clean-command is executed, all recorded statistics older than
* the number of days specified here will be deleted.
*/
'delete_statistics_older_than_days' => 60,
/*
* Use an DNS resolver to make the requests to the statistics logger
* default is to resolve everything to 127.0.0.1.
*/
'perform_dns_lookup' => false,
],
/*
* Define the optional SSL context for your WebSocket connections.
* You can see all available options at: http://php.net/manual/en/context.ssl.php
*/
'ssl' => [
/*
* Path to local certificate file on filesystem. It must be a PEM encoded file which
* contains your certificate and private key. It can optionally contain the
* certificate chain of issuers. The private key also may be contained
* in a separate file specified by local_pk.
*/
'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
/*
* Path to local private key file on filesystem in case of separate files for
* certificate (local_cert) and private key.
*/
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
/*
* Passphrase for your local_cert file.
*/
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
],
/*
* Channel Manager
* This class handles how channel persistence is handled.
* By default, persistence is stored in an array by the running webserver.
* The only requirement is that the class should implement
* `ChannelManager` interface provided by this package.
*/
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,
];

Installare Pusher Php Sdh

Per abilitare la comunicazione in tempo reale nelle applicazioni web, l'integrazione con Pusher rappresenta una soluzione potente ed efficace. Pusher PHP SDK facilita l'interazione con il servizio Pusher, consentendo di gestire facilmente le notifiche push e la trasmissione di eventi. In questa sezione, ti guideremo attraverso i passaggi necessari per installare e configurare Pusher PHP SDK. In modo che tu possa iniziare rapidamente a sfruttare le sue potenzialità. Da terminale lancia:

composer require pusher/pusher-php-server

Per eseguire il Queue o Coda da terminale lancia poi:

php artisan queue:work

Per eseguire il Websockets apri invece un altro terminale e lancia:

php artisan websockets:serve

Configurare il file broadcasting.php

Finora abbiamo installato il pacchetto WebSockets e il Pusher PHP SDK. Oltre ad aver avviato i server WebSocket e Queue. Il prossimo passo consiste nel configurare il file config/broadcasting.php perché l'applicazione possa trasmettere eventi in tempo reale utilizzando Pusher. Apri quindi il file .env e scorri fino in fondo dove dovresti vedere la chiave segreta ed il cluster dell'app Pusher:

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

Per tutti questi valori, invece di usare il server Pusher useremo il nostro. Perciò è necessario impostare il valore a staging:

PUSHER_APP_ID=staging
PUSHER_APP_KEY=staging
PUSHER_APP_SECRET=staging
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

Assicuriamoci ora che il driver di trasmissione sia impostato su Pusher:

BROADCAST_DRIVER=log

cambiandolo in:

BROADCAST_DRIVER=puscher

e aggiungiamo altre due variabili:

LARAVEL_WEBSOCKETS_HOST=127.0.0.1
LARAVEL_WEBSOCKETS_PORT=6001[/bash]
dove:

LARAVEL_WEBSOCKETS_HOST specifica l'indirizzo host del server WebSocket. In questo esempio 127.0.0.1 indica che il server WebSocket è in esecuzione sulla stessa macchina del progetto Laravel.
LARAVEL_WEBSOCKETS_PORT specifica la porta su cui il server WebSocket ascolterà le connessioni. In questo esempio, è stata scelta la porta 6001.

Modifica del file
Apri infine il file config/broadcasting.php e modificalo come di seguito:
[code lang=php]
'connections' => [
  'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
      'cluster' => env('LARAVEL_WEBSOCKETS_HOST'),
      //'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
      'port' => env('LARAVEL_WEBSOCKETS_PORT'),
      'cluster' => env('PUSHER_APP_CLUSTER'),
      'scheme' => env('PUSHER_SCHEME', 'https'),
      'encrypted' => true,
      'useTLS' => false, /*env('PUSHER_SCHEME', 'https') === 'https',*/
      'scheme' => 'http',
      'curl_options' => [
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
       ],
    ],
  ],
],
...

Conclusione

In questo tutorial, abbiamo affrontato la configurazione di un ambiente Laravel con WebSockets e Pusher per abilitare la comunicazione in tempo reale nelle applicazioni web. Abbiamo iniziato installando il pacchetto Laravel WebSockets utilizzando Composer. Questo passaggio ha incluso l'installazione di tutte le dipendenze necessarie. Registrando automaticamente un fornitore di servizi.

Successivamente abbiamo pubblicato e eseguito le migrazioni per archiviare informazioni statistiche durante l'esecuzione del server WebSocket. Abbiamo poi pubblicato il file di configurazione WebSocket, assicurandoci che fosse pronto per essere utilizzato nell'applicazione.

Abbiamo continuato installando il Pusher PHP SDK, che facilita l'interazione con il servizio Pusher. Rendendo più semplice la gestione delle notifiche push e la trasmissione di eventi. Una volta completata l'installazione, abbiamo configurato le variabili di ambiente nel file .env. Impostando correttamente l'host e la porta del server WebSocket.

Infine, abbiamo avviato i server WebSocket e Queue. Garantendo che la nostra applicazione fosse pronta per trasmettere eventi in tempo reale utilizzando Pusher. Abbiamo anche configurato il file config/broadcasting.php per integrare pienamente Pusher con il progetto Laravel.

In sintesi, è stato creato un sistema robusto per la comunicazione in tempo reale nelle applicazioni Laravel, sfruttando la potenza di WebSockets e Pusher. Ora la tua applicazione è pronta per gestire notifiche e trasmissioni di eventi in modo efficiente e affidabile.

Ti consigliamo anche