Skip to content

A simple calculator app that implements math operations via a magic _call method.

License

Notifications You must be signed in to change notification settings

kudashevs/calculator-via-magic

Repository files navigation

Calculator Via Magic

This is a case study that aims to show one of the possible ways of using magic methods in PHP language.

How it works

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.

Notes

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 to learn

Things that you can learn from this case study:

License

The MIT License (MIT). Please see the License file for more information.

About

A simple calculator app that implements math operations via a magic _call method.

Topics

Resources

License

Stars

Watchers

Forks

Languages