视图

在前面讲到的例子中,几乎都是直接对$response进行操作,然而实际上很少需要对其直接操作的情况。

在 IMI 中可以使用视图来决定响应内容和格式,包括JSON、XML、模版渲染在内的 IMI 认为都是视图,视图可以直接通过注解来设置。

  1. <?php
  2. namespace Test;
  3. use Imi\Controller\HttpController;
  4. use Imi\Server\Route\Annotation\Route;
  5. use Imi\Server\Route\Annotation\Action;
  6. use Imi\Server\Route\Annotation\Controller;
  7. use Imi\Server\View\Annotation\View;
  8. /**
  9. * 一个简单的控制器
  10. * @Controller
  11. * @View(renderType="json")
  12. */
  13. class Index extends HttpController
  14. {
  15. /**
  16. * 一个动作
  17. * @Action
  18. * @Route(url="/")
  19. * @View(renderType="html", template="index")
  20. */
  21. public function index()
  22. {
  23. return $this->response->write('hello imi!');
  24. }
  25. }

如上代码所示,@View注解可以写在类和方法的注释中。

类注解代表针对所有动作设定的视图配置,在单个方法上写注解,会覆盖类注解。

json

  1. /**
  2. * @Action
  3. * @View(renderType="json")
  4. */
  5. public function index()
  6. {
  7. // 数组
  8. $jsonData = [
  9. 'id' => 1,
  10. 'name' => 'imi',
  11. ];
  12. // 对象
  13. // $jsonData = new stdClass;
  14. // $jsonData->name = 'imi';
  15. return $jsonData;
  16. }

可选配置

  1. return [
  2. 'beans' => [
  3. 'JsonView' => [
  4. // json_encode 的参数值配置
  5. 'options' => 0,
  6. 'depth' => 512,
  7. ]
  8. ]
  9. ];

xml

  1. /**
  2. * @Action
  3. * @View(renderType="xml")
  4. */
  5. public function index()
  6. {
  7. // DOMDocument
  8. $xml = new \DOMDocument();
  9. $xml->loadXML($xmlString);
  10. // SimpleXMLElement
  11. $xml = \simplexml_load_string($xmlString);
  12. return $xml;
  13. }

模版渲染

必选配置

  1. return [
  2. 'beans' => [
  3. 'HtmlView' => [
  4. 'templatePath' => '模版文件根路径',
  5. // 支持的模版文件扩展名,优先级按先后顺序
  6. // 'fileSuffixs' => [
  7. 'tpl',
  8. 'html',
  9. 'php'
  10. ],
  11. ]
  12. ]
  13. ];

使用方式

控制器-动作

  1. /**
  2. * @Action
  3. * @View("a/b")
  4. */
  5. public function index()
  6. {
  7. return [
  8. 'content' => 'hello imi',
  9. ];
  10. }

模版文件

模版文件根路径/a/b.html

  1. <?=$content?>

运行结果:hello imi

IMI 没有造模版引擎的轮子,是因为现在 PHP 渲染 HTML 的场景越来越少,如果有需要也可以自己集成其它开源模版引擎。

其它

在控制器-动作中,除了返回数据,你还可以直接返回$this->response,如:

return $this->response->write('hello world');

你还可以直接返回@View的注解类实例:

return new \Imi\Server\View\Annotation\View([
    'template'    =>    'index',
    'renderType'=>    'html',
    'data'        =>    [
        'name'    =>    'imi',
    ],
]);