I\'m setting up a system which will carry out various calculations on primitive data, and the provide an output based on the calculation.
My main question,
If I understand your question, you've got a database containing domain data, and a lot of calculations you execute on that data. Currently, you store those calculations as strings in the database, and execute those calculations using eval()
.
There are some reasons for doing this I can imagine - it's easy to share the calculations among different calculation instances (so you can run multiple parallel calculations, or create new calculation clients (e.g. a web client, a command line client, a mobile app). It also makes managing the calculations fairly easy - they all live in a single place.
However, there are some obvious downsides:
So, you have a bunch of alternatives. In similar scenarios, I've often created a folder in my application structure with the calculations, and used file streams to load the calculation code dynamically. By using a source code control system with automated deployments, you can deploy this to any number of calculation instances.
For more complex scenarios, I've built a little domain specific language. This is perfectly possible in PHP. In your case, this would allow you to remove a lot of the housekeeping logic ($primBVal != 0
) and focus on the domain. It's non-trivial, but if you have hundreds of calculations, it might be worth it.
If I were you, I won't put calculation php in database. Why? Let say, you decided to write your system in another language, you will need to parse that php codes in db, and convert it to your new language specifics(This is worst scenario). If I were you, I will convert this to a service, and divide it into pieces. You can put each call in to job queue, after job completion, you can save results in db. You can use this service for several type of clients.
You can create functions for each calculations in order to change algorithm of calculations easily. Also, you can add new calculation as function.
First of all: don't use eval()
unless there is a good reason. And there is never a good reason.
in the worst case eval()
makes your application vulnerable to injection attacks and also it's very slow. A bit of research reveals plenty of reasons why eval is a big no-no.
If you do so and you would like to switch from PHP to another language you would still have PHP code in your database. It makes it really hard to migrate languages. You should always strive to make as many parts of your application as independent as possible.
In this case you would tight-couple the language you use, to the database. That's a bad practice.
Also the only possibilities to run your calculations from the database would be to eval them (which is bad, see above) or to disassemble the string with string operations or regex which causes unnecessary effort.
In order to solve your problem you must execute code dependent of which calculation you need. That could be either done with switch-case-statements or if-statements. But that's also not a very elegant solution. Imagine you would need to execute other operations before calculating in the future, or extend functionality. You would need to update all your cases or if-statements.
There is a nice design-pattern which is called Strategy Pattern. The strategy pattern solves problems when one use-case can be handled differently which is probably what you want.
You want to calculate something (use-case) and there are different calculation types for it (different strategies)
To implement the Strategy pattern you basically need three things.
Your interface could look like this:
<?php
interface CalculatableInterface {
public function calculate();
}
The interface will make sure that all your strategies provide a method to actually run the calculation. Nothing special.
Next you may want to have a base class that takes your calculation operators as constructor arguments and stores them into properties.
<?php
abstract class Calculatable {
protected $valueA;
protected $valueB;
public function __construct($valueA, $valueB)
{
$this->valueA = $valueA;
$this->valueB = $valueB;
}
}
Now it's getting serious. We are implementing our strategies.
<?php
class Division extends Calculatable implements CalculatableInterface {
public function calculate()
{
return ($this->valueB != 0) ? $this->valueA / $this->valueB : 'NA';
}
}
class Percentage extends Calculatable implements CalculatableInterface {
public function calculate()
{
return ($this->valueB != 0) ? (100 / $this->valueB) * $this->valueA : 'NA';
}
}
Of course you could clean this one up a bit, but what I want to point out here is the class declaration.
We are extending our Calculatable
class so that we can pass the arithmetic operations via constructor and we are implementing the CalculatableInterface
which tells our class: "Hey! You must provide a calculate method, I don't care whether you want or not.
We'll see later why this is an integral part of the pattern.
So we have two concrete classes that contain the actual code for the actual arithmetic operation. If you would ever need to, you could change it easily as you see. To add more operations just add another class.
Now we will create a class where our strategies can be injected. Later you will instantiate an object of this class and work with it.
Here is how it looks like:
<?php
class Calculator {
protected $calculatable;
public function __construct( CalculatableInterface $calculatable )
{
$this->calculatable = $calculatable;
}
public function calculate()
{
return $this->calculatable->calculate();
}
}
The most important part here is the constructor. See how we type-hint our interface here. By doing that we make sure that only an object can be injected (Dependency Injection) whose class implements the interface. We do not need to demand a concrete class here. That's the crucial point here.
Also there's a calculate method in there. It's just a wrapper for our strategy to execute it's calculate method.
So now we just need to create an object of our Calculator
class and pass an object of one of our strategy classes (that contain the code for the arithmetic operations).
<?php
//The corresponding string is stored in your DB
$calculatable = 'Division';
$calc = new Calculator( new $calculatable(15, 100) );
echo $calc->calculate();
Try replacing the string stored in $calculatable
to Percentage
and you see that the operation for calculating the percentage will be executed.
The strategy pattern allowed you to create a clean interface for working with dynamic tasks that are only made concrete during runtime. Neither your database needs to know how we calculate things, nor your actual calculator does. The only thing we need to make sure is to code against an interface that provides a method to let us calculate things.
I run a market research site where indeed many computes need to be done, performance indexes mainly. my experience and my actual work tells me that you should use php scripts instead of database strings, added on the fly. This because you have a workflow which can be better managed by moving and removing pieces of code . The database should work well as the workflow. manager or processs paramount .