How to make such a chat, BUT it is not a common room for users, but it is necessary to make it so that two users connect and communicate with each other. How to do it? How to choose (determine how many users are online now) of these users from all? What technologies to use? Where to keep correspondence (albeit temporarily or as an option - permanently)?

  • Where and how you like. No, well, really. - andreymal
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • Often take the ready decision for a chat. In php redirect requests there and answers from there. In this case, it is possible to make participation in the chat of outsiders (not from your site), if necessary. - Sergey

3 answers 3

Here is a small sketch of the class hierarchy and their interactions. I will deliberately miss many nuances, but I think the general idea will become clear to you.

Data structure:

#таблица пользователей User id | login | password #таблица чат-комнат ChatRoom id | max_user #таблица отношений пользователь-чат (многие-ко-многим) UserChat id | user_id | chat_room_id | joined #таблица для хранения сообщений в чат комнатах ChatMessage id | user_chat_room_id | message | posted_at 

Class User.php:

 class User { // в классе пользователя реализуем методы логина в систему, // получения чат комнат, в которых состоит пользователь и т.д., а также // CRUD операции /** * Отправка нового сообщения в чат */ public function postMessage(ChatRoom $chatRoom, $msg) { // Проверка: имеет ли пользователь доступ в комнату? if ( $chatRoom->checkUserAccess($this) ) { // Если имеет, создаем новое сообщения и сохраняем его в базе $chatMsg = new ChatMessage($chatRoom, $user, $msg); $chatMsg->save(); } } } 

Class ChatRoom.php:

 class ChatRoom { private $id; private $maxUser; public __construct($maxUser) { $this->maxUser = $maxUser; } public function save() { // обращение к базе данных, записываем данные в базу } // ...реализовываем остальные CRUD-операции.. /** *Метод проверки имеет ли пользователь доступ к чату */ public function checkUserAccess(User $user) { $userId = $user->getId(); $userChat = new UserChat(); // Делегируем проверку методу модели UserChat, которая ищет в таблице UserChat запись с соответствующими chat_room_id и user_id return $userChat->findBy($this->id, $userId); } public function getInvitedUsers() { // метод находит в базе и возвращает массив приглашенных в комнату пользователей } // Пригласить пользователя в чат public function invite(User $user) { // проверяем можно ли пригласить еще одного пользователя в чат if ( count($this->getInvitedUsers() < $this->maxUser ) { $userChat = new UserChat($this, $user); // создается новая запись в таблице UserChat, с user_id приглашенного пользователя и chat_room_id текущей комнаты $userChat->save(); } } public function getMessages() { // метод возвращает все сообщения из ChatMessages, для текущей комнаты } public function getMessagesSince($time) { // возвращает все сообщения, отправленные после $time, используется для обновления данных во время разговора } } 

The remaining classes are not painted - there by and large simple CRUD operations. Using instances of these classes you can assemble a simple chat room. To update the data in real time, I recommend reading about WebSocket . And for not quite honest real time, you can use an ajax request that will receive data (via the ChatRoom::getMessagesSince($time) method) at a specified time interval and / or by clicking on the "update" button.

The topic is extensive, so it was answered with very "broad strokes". I also want to add that in my code examples the same classes are responsible for database queries and the logic of domain objects - this is done only for clarity, and I strongly recommend that you do not do this and put the logic of working with the database into separate objects . Hope I managed to help.

    If you need well, right in "Real time", then dig in the direction of sockets and node.js. Otherwise, it turns out that clients must send requests to the server and check - "Is there no messages for them"

    • Amendment: websocket. And node.js is not necessary for this to touch. - D-side

    Not needed for a simple PHP chat, need P2P . You can use both native webRTC and skylink have alternatives, for example PeerJS, Pusher etc. The minimum chat is obtained ~ 20 lines of Javascript.

    Storage of correspondence: localStorage + synchronization algorithm. To extend this functionality, a server can actually be useful, but this is quite enough for basic chat features. Moreover, Offline-first is the design principle, implying the operation of the application without access to the server. And you need to build up gradually. The reverse is a common mistake beginners make when designing.

    • For a reliable P2P, you still need a server, be it TURN or your own fallback. And WebRTC DataChannel, I remember, is not in Edge, and this is a very bad thing. - D-side
    • Of course, needed. That's why I gave the link to skylink and hinted that there are other TURN / STUN providers. As for cross-browser compatibility, there was no such task with a top-starter, however, it is obvious that this solution has its own uses. Even industrial, for example, surrounded by a crosswalk. So I do not understand your minus, not too lazy to put. - 11111000000
    • It's just that the solution through P2P at the moment has even more problems than the centralized one on websockets. Therefore a minus. - D-side
    • Centralization has its own problems. And the future is for p2p, obviously. It already works quite well. There are already several specialized providers TURN / STUN. Yes, this is not about PHP, but WebRTC is designed for normal modern languages ​​and is implemented in hardware and, by the Occam's razor, this is the most correct and easiest way to make a chat. - 11111000000
    • Spitting on PHP :) With P2P you just have to solve even more tasks, the author was interested in them: (a) where to store the story? (b) how to monitor the number of users online? (c) who to connect with? You have not answered all of this. - D-side