Skip to content

A simple calculator app that implements math operations via a dependency injection.

License

Notifications You must be signed in to change notification settings

kudashevs/calculator-via-injection

Repository files navigation

Calculator Via Injection

This is a case study that aims to show one of the possible ways of injecting functionality in PHP language.

How it works

We are given a Calculator class that requires an instance of Calculable as its constructor parameter. The Calculable is just an abstraction of some calculations, which are represented by a calculate method, that accepts a variable number of arguments (variadic function). To start using the injection, we need to define a piece of functionality (a math operation in our case) that conforms to our abstraction, and provide its instance to the Calculator at the moment of its instantiation. The instance of Calculator is going to retain the injected functionality and use it each time the calculation is requested.

$addition = new Calculator(new Addition());
echo $addition->calculate(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 uses the Validator trait to perform validation. The Division class overrides the default trait's method and extends its functionality. For more information see the Operations folder).

The validation of input arguments is implemented in the Validator trait. Therefore, every operation might use the trait for validation, or might not. We don't force the Calculable implementations to use the predefined validation.

Note The decomposition might look strange, and it really is. However, this is just a study case on how we can use the dependency injection to assign some predefined behavior to a variable. It almost imitates a closure study case.

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 dependency injection.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages