IMHO, you should use Polymorphism.
This video can help you understand this principle.
Here is my way of thinking.
First, define an interface for any operations you need.
interface OperationInterface { public function evaluate(array $operands = array()); }
Then create a calculator holder
class Calculator { protected $operands = array(); public function setOperands(array $operands = array()) { $this->operands = $operands; } public function addOperand($operand) { $this->operands[] = $operand; } public function setOperation(OperationInterface $operation) { $this->operation = $operation; } public function process() { return $this->operation->evaluate($this->operands); } }
Then you can define an operation, for example, adding
class Addition implements OperationInterface { public function evaluate(array $operands = array()) { return array_sum($operands); } }
And you would use it like:
$calculator = new Calculator; $calculator->setOperands(array(4,2)); $calculator->setOperation(new Addition); echo $calculator->process();
For this purpose, if you want to add some new behavior or change an existing one, simply create or edit a class.
For example, say you want to work with the module
class Modulus implements OperationInterface { public function evaluate(array $operands = array()) { $equals = array_shift($operands); foreach ($operands as $value) { $equals = $equals % $value; } return $equals; } }
Then
$calculator = new Calculator; $calculator->setOperands(array(4,2)); $calculator->setOperation(new Addition); // 4 + 2 echo $calculator->process(); // 6 $calculator->setOperation(new Modulus); // 4 % 2 echo $calculator->process(); // 0 $calculator->setOperands(array(55, 10)); // 55 % 10 echo $calculator->process(); // 5
This solution allows your code to be a third-party library.
If you plan to reuse this code or give it as a library, the user will not modify your source code in any way.
But what if he needs a Substraction or BackwardSubstraction method that is not defined?
He just needs to create his own Substraction class in his project, which implements OperationInterface to work with your library.
Easier to read
When searching in the project architecture it’s easier to see such a folder
- app/ - lib/ - Calculator/ - Operation/ - Addition.php - Modulus.php - Substraction.php - OperationInterface.php - Calculator.php
And immediately find out which file contains the desired behavior.