Reputation: 9008
Usually in Zend Framework to in the routing configuration it is specified the action and the controller that need to be use to answer a particular request.
Then in the controller class it is needed an somethingAction
method that correspond to the action provided in the configuration.
Is is possible to use the __invoke
method of the controller as an Action?
Otherwise, is it possible to specify any type of callable instead of an object method?
Upvotes: 0
Views: 250
Reputation: 13558
Is is possible to use the __invoke method of the controller as an Action?
Yes. The abstract controller's onDispatch()
figures out what method to call. If you simply override the onDispatch()
with your custom logic, you can call whatever method you want. An example (not tested):
public function onDispatch(MvcEvent $e)
{
$routeMatch = $e->getRouteMatch();
if (!$routeMatch) {
throw new Exception\DomainException('Missing route matches');
}
$action = $routeMatch->getParam('action', 'not-found');
$method = '__invoke';
if (!method_exists($this, $method)) {
$method = 'notFoundAction';
}
$actionResponse = $this->$method($action);
$e->setResult($actionResponse);
return $actionResponse;
}
This way the __invoke()
should be called with a single argument, the action it had in the route match.
Otherwise, is it possible to specify any type of callable instead of an object method?
Not really. ZF2 determines the controller by a Dispatchable
interface. As long as a class implements that interface, it is an controller. The standard action controller implements the onDispatch()
and figures out the action to call, but that is not necessary. In ZF2 it is not possible to use any callable you want.
Upvotes: 1