This is a case study that aims to show one of the possible ways of using magic methods in PHP language.
We are given a Calculator class with the only one __call
method. This is so-called "magic method",
which is triggered when an inaccessible method is called on an object. This magic method accepts the name of a method being
called and an array of the provided arguments. When the __call
method is triggered, a Calculator
instance is trying
to identify an Operation
that corresponds to the received method name. If the suitable Operation
exists, a Factory
creates an instance of the operation and the Calculator
class performs calculations using this instance. If not, it
throws an exception as if there were no such method.
$calculator = new Calculator();
echo $calculator->addition(1, 2); // results in 3
for more usage examples, please see the examples folder.
By default, the package provides four classes that correspond to the basic math operations (addition, subtraction,
multiplication, division). Each class extends an Operation
class. The Operation
class is an abstract class that
obliges its subclasses to implement the performCalculation
method. It also provides default implementations for
calculate
and validate
methods. The Division
class overrides the default implementation of the validate
method
and extends its functionality. For more information see the Operations folder.
The validation of input arguments is implemented in the Operation abstract class. By using
the final
keyword and the inheritance, we force all the Operation
implementations to use the predefined validation.
A lookup table for supported operations is kept as a constant in the Factory.php file.
Things that you can learn from this case study:
- magic methods, how they work, and how you can use them
- how to use the factory pattern (one of the possible implementations)
- how to use final to force the subclasses to use predefined behavior
- how to override and extend methods inherited from the base class
The MIT License (MIT). Please see the License file for more information.