Zend Framework 2 - 可调用 class 作为动作

Zend Framework 2 - Invokable class as action

通常在 Zend Framework 中的路由配置中指定需要用于响应特定请求的操作和控制器。

然后在控制器中 class 需要一个 somethingAction 方法来对应配置中提供的操作。

是否可以将控制器的 __invoke 方法用作 Action?

否则,是否可以指定任何类型的可调用对象而不是对象方法?

Is is possible to use the __invoke method of the controller as an Action?

是的。抽象控制器的 onDispatch() 算出 what method to call。如果您只是用您的自定义逻辑覆盖 onDispatch(),您可以调用任何您想要的方法。示例(未测试):

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;
}

这样 __invoke() 应该用一个参数调用,它在路由匹配中的动作。

Otherwise, is it possible to specify any type of callable instead of an object method?

不是真的。 ZF2 通过 Dispatchable 接口确定控制器。只要 class 实现了那个接口,它就是一个控制器。标准动作控制器实现 onDispatch() 并找出要调用的动作,但这不是必需的。在 ZF2 中,不可能使用任何你想要的可调用对象。