yakczh
V2EX  ›  问与答

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

  •  
  •   yakczh · Nov 2, 2014 · 2694 views
    This topic created in 4240 days ago, the information mentioned may be changed or developed.
    对于同样的业务逻辑,可能是页面get/post请求 后,套上模板输出,也可以是ajax请求后输出json数据
    一般是写if else 判断 
    if( $this->isAjax() ) { 
    xx }  else {
    oo
    }

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

    另外,可能需要在没有 format 参数是给一个默认值
    chemzqm
        4
    chemzqm  
       Nov 3, 2014
    根据http规范应该检查accept,考虑到accept是多个值组成的字段,一般是优先输出html然后json。如果你想做框架给别人用的话,最好不要做多余的假定
    virusdefender
        5
    virusdefender  
       Nov 3, 2014
    参考做rest api格式
    a.com/1/?format=json
    a.com/1/?format=xml
    你可以没有后缀就默认html或者检测accept
    coldwinds
        6
    coldwinds  
       Nov 3, 2014
    negotiation
    yakczh
        7
    yakczh  
    OP
       Nov 4, 2014
    $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);
    });
    });
    });


    这种写法感觉比较丑
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2866 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 01:14 · PVG 09:14 · LAX 18:14 · JFK 21:14
    ♥ Do have faith in what you're doing.