I have come across this problem before and expect to do so again: I want to run a subtotal calculation in both javascript and PHP. I may want to change the calculation at some point.
- It needs to run in javascript to maximise the speed of the calculation, so that the user knows what to expect.
- It needs to run in PHP so that I am getting a valid subtotal which a malicious user cannot interfere with.
As such:
- If I only run the calculation on the client-side (in javascript), a malicious user may hack the javascript and change the subtotal.
- If I only run the calculation on the server-side (in PHP), an AJAX call would have to be waited on for the user to get their updated subtotal.
So I want to perform the calculation on both sides. The only way I have seen this done is by programming the calculation in PHP and programming the calculation in separate javascript.
My question is, what pattern, technique or technology would people recommend that I use to create the calculation on the server-side and make it compatible with javascript when it is sent to the client-side?
An idea I had, for example, was a PHP array for the calculation, which gets translated into PHP code and javascript code, e.g:
array(
array(type => "operand", "name" => "variable_A"),
array(type => "operator", "name" => "multiply"),
array(type => "operand", "name" => "variable_B"),
)
This might convert into PHP:
return $variable_A * $variable_B;
And into Javascript:
return variable_A * variable_B;
That's an example operational pattern. I don't know what real ones would look like if they exist.