视图

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

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

    1. /**
    2. * @Action
    3. * @View(renderType="json")
    4. */
    5. public function index()
    6. {
    7. // 数组
    8. $jsonData = [
    9. 'id' => 1,
    10. ];
    11. // 对象
    12. // $jsonData = new stdClass;
    13. // $jsonData->name = 'imi';
    14. return $jsonData;
    15. }
    1. 'beans' => [
    2. 'JsonView' => [
    3. // json_encode 的参数值配置
    4. 'options' => 0,
    5. 'depth' => 512,
    6. ]
    7. ]
    8. ];
    1. return [
    2. 'beans' => [
    3. 'HtmlView' => [
    4. // 支持的模版文件扩展名,优先级按先后顺序
    5. // 'fileSuffixs' => [
    6. 'tpl',
    7. 'html',
    8. 'php'
    9. ]
    10. ]
    11. ];

    控制器-动作

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

    模版文件

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

    运行结果:hello imi

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

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

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

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