This is a case study that aims to show one of the possible ways of injecting functionality in PHP language.
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.
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 that you can learn from this case study:
- how the constructor dependency injection works
- how to delegate calls/messages to another object
- how to override and extend methods inherited from traits
The MIT License (MIT). Please see the License file for more information.