如前所述,控制器在Zend MVC框架中起着重要的作用。应用程序中的所有网页都需要由控制器处理。
在Zend MVC框架中,控制器是实现– Zend / Stdlib / DispatchableInterface的对象。所述DispatchableInterface有一个方法,调度,它获取该请求对象作为输入,做一些逻辑,并返回对应措施的对象作为输出。
dispatch(Request $request, Response $response = null)
一个返回“ Hello World”的Controller对象的简单示例如下-
use Zend\Stdlib\DispatchableInterface; use Zend\Stdlib\RequestInterface as Request; use Zend\Stdlib\ResponseInterface as Response; class HelloWorld implements DispatchableInterface { public function dispatch(Request $request, Response $response = null) { $response->setContent("Hello World!"); } }
该DispatchableInterface是基本的,它需要大量的其他接口编写高水平的控制器。一些这样的接口如下-
牢记这些注意事项,Zend框架提供了许多现成的控制器来实现这些接口。最重要的控制器如下所述。
在Zend MVC框架中,AbstractActionController(Zend / Mvc / Controller / AbstractActionController)是最常用的控制器。它具有编写典型网页的所有必要功能。它允许路由(路由将请求url与控制器及其方法之一进行匹配)匹配action。匹配后,控制器将调用以该动作命名的方法。
例如,如果某个路由测试匹配且该路由测试返回hello进行操作,则将调用helloAction方法。
让我们使用AbstractActionController编写TutorialController。
完整的代码清单如下-
?php namespace Tutorial\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class TutorialController extends AbstractActionController { public function indexAction() { return new ViewModel(); } }
我们已经成功添加了新的TutorialController。
AbstractRestfulController(Zend \ Mvc \ Controller \ AbstractRestfulController)检查传入请求的HTTP方法,并通过考虑HTTP方法来匹配操作(方法)
例如,如果在请求中找到id参数,则使用GET HTTP方法的请求将与getList()方法或get()方法匹配。
AbstractConsoleController(Zend \ Mvc \ Controller \ AbstractConsoleController)与AbstractActionController相似,只是它仅在控制台环境中运行,而不在浏览器中运行。