Answer the question
In order to leave comments, you need to log in
Is it a bad idea to configure classes/services with closures rather than, for example, arrays?
Many libraries have the ability to load a configuration from an array (or any configuration file). Wouldn't it be a better idea to configure the service with a closure or any other callable (Class::__invoke() for example)?
To illustrate:
class Router
{
public function __construct(Closure $config)
{
$closure($this);
}
public function addRoute(...$params) {
// some code
}
}
return function($router) {
$router
->addRoute('/')
->setName('home')
;
// and so on....
}
$router = new Router(include 'config/router.php');
$controller = $router->match('/some/path');
Answer the question
In order to leave comments, you need to log in
No, not better.
Configs may need to be merged, cached, etc. In the same ZF2, the config of one module can override the values of another or even global application settings. With closures, it won't be so easy.
But even if you do this, then go even further, to the end, just create an inheritor of class MyRoute extends Route , and as a result, the code will be simpler:
$router = new MyRoute();
$controller = $router->match('/some/path');
It looks good, but it's better to pass the function not to the constructor, but to some method. Then, for classes configured in this way, it will be possible to use an impurity, something like this:
trait ClosureConfigurable {
public function configureWith(Closure $closure) {
$closure($this);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question