PHP Classes

How to Implement a PHP Chat Server based on Server-Sent Events Using the Package Chat SSE: Exchange chat messages using server-sent events

Recommend this page to a friend!
  Info   View files Example   View files View files (15)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-05-22 (10 days ago) RSS 2.0 feedNot yet rated by the usersTotal: 8 This week: 2All time: 11,324 This week: 29Up
Version License PHP version Categories
chat-sse 1.0MIT/X Consortium ...5HTTP, PHP 5, Chat
Description 

Author

This package can exchange chat messages using server-sent events.

It implements a chat system that receives messages from chat users.

The messages are stored in a database and are sent to other chat users using server-sent events.

The package uses a Web server written in Python that supports server-sent events.

Innovation Award
PHP Programming Innovation award nominee
May 2024
Nominee
Vote
Server-sent events are messages that a Web server can send to browsers connected to the server when relevant events happen on the server side.

This package implements a chat system that uses server-sent events to distribute messages to multiple users who participate in chat rooms.

Manuel Lemos
Picture of Rodrigo Faustino
  Performance   Level  
Name: Rodrigo Faustino <contact>
Classes: 19 packages by
Country: Brazil Brazil
Innovation award
Innovation award
Nominee: 14x

Winner: 1x

Example

<?php

require 'vendor/autoload.php';
use
Chat\App\Chat;

header('Content-Type: application/json');

if (
$_SERVER['REQUEST_METHOD'] === 'POST') {
   
$data = json_decode(file_get_contents('php://input'), true);
   
$message = $data['message'] ?? '';
   
$user = $data['usuario'] ?? '';
   
$chat = new Chat();
   
$success = $chat->sendMessage($message,$user);

    if (
$success) {
        echo
json_encode(['status' => 'success', 'message' => 'Mensagem enviada com sucesso.']);
    } else {
       
http_response_code(500);
        echo
json_encode(['status' => 'error', 'message' => 'Falha ao enviar a mensagem.']);
    }
} else {
   
http_response_code(405);
    echo
json_encode(['status' => 'error', 'message' => 'Método de solicitação não permitido.']);
}



Details

Chat em Tempo Real com PHP e FastAPI

Este projeto implementa um sistema de chat em tempo real utilizando PHP e FastAPI. Ele inclui a integração do padrão Observer com Server-Sent Events (SSE) para notificação em tempo real e permite a interação com um banco de dados compartilhado entre as duas tecnologias.

Tecnologias Utilizadas

  • PHP
  • FastAPI (Python)
  • Server-Sent Events (SSE)
  • MySQL (ou outro banco de dados relacional)
  • JavaScript
    ## Estrutura do Projeto
    /appphp
    /src
        Chat.php
        Database.php
    send_message.php
    sse.php
    /apppython
    /app
        main.py
        routes/
            message_routes.py
        models/
            message.py
        database/
            database.py
    requirements.txt
    
    ## Padrão Observer e Server-Sent Events
  • Padrão Observer O padrão Observer é um padrão de design comportamental que define uma dependência um-para-muitos entre objetos, permitindo que quando um objeto muda de estado, todos os seus dependentes sejam notificados e atualizados automaticamente. Neste projeto, usamos o padrão Observer para notificar os usuários do chat sobre novas mensagens.
  • Server-Sent Events (SSE) SSE é uma tecnologia que permite que o servidor envie atualizações automáticas para o navegador. Utilizamos SSE para implementar a comunicação em tempo real entre o servidor e o cliente, enviando mensagens do servidor para o navegador assim que elas são adicionadas ao banco de dados. https://developer.mozilla.org/pt-BR/docs/Web/API/Server-sent_events/Using_server-sent_events ## Configuração do Projeto
  • Configuração do PHP Instalação das Dependências Certifique-se de ter o Composer instalado e execute:
composer install

Configuração do Banco de Dados Crie o banco de dados e a tabela de mensagens:

CREATE TABLE `messages` (
  `id` int NOT NULL AUTO_INCREMENT,
  `message` text NOT NULL,
  `usuario` varchar(50) NOT NULL,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)

executar o servidor python

na pasta do projeto

pip install -r requeriments.txt

python main.py

<img src="chat.PNG">


  Files folder image Files  
File Role Description
Files folder imageappphp (4 files, 1 directory)
Files folder imageapppython (1 file, 3 directories)
Accessible without login Image file chat.PNG Data Auxiliary data
Accessible without login HTML file chatphp.html Doc. Documentation
Accessible without login HTML file index.html Doc. Documentation
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  appphp  
File Role Description
Files folder imagesrc (2 files)
  Accessible without login Plain text file composer.json Data Auxiliary data
  Accessible without login Plain text file composer.lock Data Auxiliary data
  Accessible without login Plain text file send_message.php Example Example script
  Accessible without login Plain text file sse.php Example Example script

  Files folder image Files  /  appphp  /  src  
File Role Description
  Plain text file Chat.php Class Class source
  Plain text file Database.php Class Class source

  Files folder image Files  /  apppython  
File Role Description
Files folder imagedatabase (2 files)
Files folder imagemodels (1 file)
Files folder imageroutes (1 file)
  Accessible without login Plain text file main.py Data Auxiliary data

  Files folder image Files  /  apppython  /  database  
File Role Description
  Accessible without login Plain text file config.py Data Auxiliary data
  Accessible without login Plain text file database.py Data Auxiliary data

  Files folder image Files  /  apppython  /  models  
File Role Description
  Accessible without login Plain text file message.py Data Auxiliary data

  Files folder image Files  /  apppython  /  routes  
File Role Description
  Accessible without login Plain text file message_routes.py Data Auxiliary data

 Version Control Unique User Downloads Download Rankings  
 100%
Total:8
This week:2
All time:11,324
This week:29Up