V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yakczh
V2EX  ›  问与答

web 框架 对于同样的 action 操作,不同输出方式,怎么样设计比较优雅

  •  
  •   yakczh · 2014-11-02 21:05:37 +08:00 · 2030 次点击
    这是一个创建于 3470 天前的主题,其中的信息可能已经有所发展或是发生改变。
    对于同样的业务逻辑,可能是页面get/post请求 后,套上模板输出,也可以是ajax请求后输出json数据
    一般是写if else 判断 
    if( $this->isAjax() ) { 
    xx }  else {
    oo
    }

    如果要统一封装下,怎么样设计比较好
    7 条回复    2014-11-04 22:27:50 +08:00
    bigredapple
        1
    bigredapple  
       2014-11-02 21:23:17 +08:00
    看 Accept
    abelyao
        2
    abelyao  
       2014-11-03 00:24:00 +08:00
    有一些框架自带了 GET / POST 的判断,
    甚至有一些在配置 router 的时候可以指定 GET 和 POST 使用不同的处理方式。
    qiayue
        3
    qiayue  
       2014-11-03 01:08:09 +08:00
    多带一个 format 参数, format 为 html 则输出 html ,为 json 则输出 json
    你可以把 html 和 json 当做不同的模板,那么 action 中只需要指定模板为 format 的值即可

    另外,可能需要在没有 format 参数是给一个默认值
    chemzqm
        4
    chemzqm  
       2014-11-03 01:35:59 +08:00
    根据http规范应该检查accept,考虑到accept是多个值组成的字段,一般是优先输出html然后json。如果你想做框架给别人用的话,最好不要做多余的假定
    virusdefender
        5
    virusdefender  
       2014-11-03 08:36:40 +08:00
    参考做rest api格式
    a.com/1/?format=json
    a.com/1/?format=xml
    你可以没有后缀就默认html或者检测accept
    coldwinds
        6
    coldwinds  
       2014-11-03 12:48:28 +08:00
    negotiation
    yakczh
        7
    yakczh  
    OP
       2014-11-04 22:27:50 +08:00
    $app->path('posts', function($request) use($app) {
    $app->get(function($request, $postId) use($app) {
    // Prepare your data ONCE
    $data = array(
    array('title' => 'Foo', 'author' => 'Calvin'),
    array('title' => 'Bar', 'author' => 'Hobbes')
    );

    // Respond in multiple formats
    $app->format('json', function($request) use($app, $data) {
    return $data;
    });
    $app->format('html', function($request) use($app, $data) {
    return $app->template('posts', $data);
    });
    });
    });


    这种写法感觉比较丑
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2378 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:42 · PVG 19:42 · LAX 04:42 · JFK 07:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.