How to avoid repeating business logic between client and server?

You can do one more thing.

Create your validation and business logic code with JavaScript only. But make it very loosely coupled, as much as possible. If possible, only take JSON as input and give JSON as output.

Then set up a separate NodeJS server alongside the existing PHP server to serve that logic to the client, so that on the client side it can be used without an AJAX call.

Then from the PHP server, when you need to validate and run all those business logic rules, use cURL to call the NodeJS business logic and validate the data. That means an HTTP call from the PHP server to the NodeJS server. The NodeJS server will have additional code which will take the data, validate with the same code, and return the result.

By this way you can make

  1. Faster development - one place to unit test your logic.
  2. Faster client code execution - no need for AJAX, since the same validation JavaScript code is being served by NodeJS to your client.
  3. All business logic lives in the NodeJS server - when business logic changes, you only need to touch this part; so that in the near future, if you need to create some other additional interfaces, then you can use this server to validate your data. It will work just like your Business Rule Server.

The only thing you need to do is setup a NodeJS server alongside your PHP server. But you do not need to change all of your code to run on the NodeJS server.


I had the same issue when I decided to create an application using Laravel for back end, and Angular 2 for front-end. And it seems to me there is no solution to avoid the business logic duplicate so far, because:

At the moment PHP and JavaScript cannot be converted from one to another. Would it be nice if we can use same language for writing the business logic and then embed them into both back-end and front-end. From this point it leads me to another point:

To achieve the goal, we should write the business logic in one language only, and so far JavaScript is the best solution. As you know TypeScript/EMCA Script help us to write the code in the OOP way. Meteor framework NodeJS infrastructure help us to write code in JavaScript for running in both sides Back-end and front-end.

So from my point of view, we can use TypeScript/EMCA to write packages for business logic, for example a class for validation written in JavaScript can be implemented both side, so you just write one time only, but it will be called twice from front-end and back-end also.

That's my point. Hope to see some other solutions for this very interesting topic.