This gist is about:
- https://twitter.com/taylorotwell/status/600680897550098432
- https://twitter.com/Ocramius/status/600705252539691008
Mainly:
function
cannot (should not) be used when side-effects occurfunction
does not work with dependency injectionfunction
is not testable in isolation if it isn't a pure function without dependencies
In order to fix the problems exposed above, and avoid global or static scope pollution, two approaches are possible:
- using a
Closure
, combined with a higher order function (also called functor) - using an
object
that implements the__invoke
magic method
Few notes:
-
a class that only implements
__invoke
and__construct
is basically afunction
combined with afunctor
-
a class can be easily tested in isolation
-
a
Closure
with dependencies cannot be tested in isolation -
in order to make a
Closure
testable in isolation, it must be combined with a higher order function -
there is no runtime difference between using a
Closure
and any object with an__invoke
method defined in its class -
in PHP,
$a = function () use (...) {}
simply means "call the constructor of classClosure
with these parameters and this body for__invoke
", so you end up with an object that implements__invoke
anyway.
Therefore, object
+ __invoke
is much simpler and flexible than using
a Closure
, whereas a function
is not applicable in any context that
requires the usage of DI.
Thank you for sharing knowledge and congratulations on the gist
A small adjustment that can be made in the example closure.php would be:
for