This gist is about:
- https://twitter.com/taylorotwell/status/600680897550098432
- https://twitter.com/Ocramius/status/600705252539691008
Mainly:
functioncannot (should not) be used when side-effects occurfunctiondoes not work with dependency injectionfunctionis 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
objectthat implements the__invokemagic method
Few notes:
-
a class that only implements
__invokeand__constructis basically afunctioncombined with afunctor -
a class can be easily tested in isolation
-
a
Closurewith dependencies cannot be tested in isolation -
in order to make a
Closuretestable in isolation, it must be combined with a higher order function -
there is no runtime difference between using a
Closureand any object with an__invokemethod defined in its class -
in PHP,
$a = function () use (...) {}simply means "call the constructor of classClosurewith these parameters and this body for__invoke", so you end up with an object that implements__invokeanyway.
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