0

How would I create for example a live chat, where you "post" a piece of text and it is displayed to other users in a "chat room", without the need of permanently storing it.

My initial idea would be to create an object: chat room where the last couple of messages are stored as attributes in an array or something, but I don't know how and if I could make the same object accessible to multiple users with individual sessions.

My second (and less preferred) idea would to use redis and store the data for a short time.

A nudge in the right direction would be greatly appreciated.

2 Answers 2

2

Most web-based chat rooms are done with websockets, which PHP has support for.

The general websocket workflow in any supporting language would be roughly:

have a list of people who are connected to the 'room' and the associated websocket connection object for each user kept in memory. When a user sends their own message through the websocket, the server receives that message and a reference to the room it is for. The room id is used to find all users who are connected. The message is then sent back down the stored websocket connections to those users.

The messages are never necessarily stored in any database (redis, sql, nosql or anything else) and are only available to the users who are, at the time the message is sent, currently connected.

Sending the messages again to a user who connects later may be possible but would require a lot of extra work

That being said, PHP is probably not an ideal language for it in most setups because each request is far more separate from the previous then other languages, meaning websocket connections can't be stored and reused between requests. But you can do it with lambda functions and API gateway on AWS, if you feel like diving into the cloud. Otherwise, you may wish to look at other languages.

2

If you're using PHP, each request may be handled by a different process, so an in-memory solution within the PHP process won't work. REDIS or a similar separate in-memory database that runs in a separate process may be the most suitable solution.

1
  • And even if the requests are handled by the same process, PHP generally uses a share-nothing architecture, where code handling different requests is not able to access the same object in memory.
    – bdsl
    May 7, 2022 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.