How to avoid repeating logic for client- and server-side?
Let's say I create a game like Scrabble. It uses a client-side scripting to handle user interface and server-side code to store games, moves etc.
Now, I would like to let users know if their move is correct. If they place a tile on a field they weren't supposed to, the game lets them know by disabling the OK button or whatever. But the same validation takes place on server side obviously in case someone tries to use the API directly.
What are the possibilities to avoid repeating the game rules in JavaScript and PHP? Some ideas I can think of:
Just validate on the server side and use Fetch/Ajax to know if the movement can be done. I don't like this idea though, because the response won't be instant.
Protect the API some other way to be sure that the movement came from the client. I don't like this idea neither, because there is no 100% method and I wouldn't like to end up with screwed up games.
Use Node.js to have it all in JavaScript. I'm not sure how much Node.js can be easily shared with the client-side code, but it's probably the idea that is closest to having just one codebase. I don't use Node.js, but I could consider having is as a service for this single purpose.
What do you guys think? My current approach is to just ignore the DRY principle and having my code in PHP and JS. That is not something I'm proud of though.
If you're not comfortable writing a back-end in Node, there are also ways to build a reactive PHP application. You could try setting up a real-time websockets server in PHP (ReactPHP is a good resource).
In this scenario you would simply send all the client's inputs to the back-end and let the back-end verify the moves. That should make it possible for you to have near real-time responses.
Yes, I forgot to include that as one of the points. I'm not sure how instant are the responses in practice. For this purpose, the decent solution should provide 100% instant responses.
@ROBOROBOK - It also depends on the user's connection, distance to server, and if you have any extra processing on your back-end (like retrieving information from a database).
The only way to receive the fastest performance possible, is to duplicate the game logic and execute it locally. If you also want to re-use the code, I'm guessing your only option is a Node.js back-end.
To be honest I'm just asking from curiosity. I used to duplicate the code, but web sockets seems like a good idea. However, in some projects it could be an overhead to use web sockets just for this purpose. In a game, on the other hand, web sockets are useful to have anyway.