好的做法呢? PHP MVC控制器阿贾克斯 [英] Good practice? PHP MVC Controller Ajax

查看:187
本文介绍了好的做法呢? PHP MVC控制器阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很好的做法来处理正常和Ajax调用一个控制器:

Is this a good practice to handle normal and ajax calls with one controller:

<?php

class SomeController extends Controller {

    function index() {

         if(!$this->input->is_ajax_request()) {
             // load model
             // create form
             // pass data to view
             // ...
         } else {
            // validate input
            // load model
            // write data to database
            // return with some json string
         }

    }

}

有哪些优点和缺点?

What are the advantages and disadvantages?

推荐答案

简短的回答:这取决于

只有 XHR (什么样的营销人所说的AJAX)和普通浏览器请求之间的真正区别是XHR希望以不同的形式响应。

Only real difference between XHR (what marketing people call "AJAX") and ordinary browser request is that XHR expects a different form of response.

在MVC风格的模式为网络的一部分,这是负责产生的反应是查看的实例。视图应该认识到,它必须产生何种反应,并采取相应的行动。在这种情况下控制器的作用就只能是改变当前视图的状态。

In the MVC-inspired patterns for web the part that is responsible for generating response are the view instances. The view should recognize, which kind of response it has to produce, and act accordingly. Controllers role in this scenario would only be to change the state of current view.

另外,你可以在引导阶段,检测接受 HTTP标头,并根据该初始化不同观点的实例。

Alternatively, you can, at the bootstrap stage, detect the Accept HTTP header, and based on that initialize a different view instance.

<子>以全面贯彻视图我的意思是一个实例,其中包含的UI逻辑是MVC的,并可以决定这对于回应。这种反应可以是HTML文件,从多个模板,JSON / XML文件或只是一个简单的HTTP头组成。

  • 优点:关注适当分离,维护更方便
  • 缺点:必须实行全员MVC

  • Pros: proper separation of concerns, easier to maintain
  • Cons: have to implement full MVC
  • ..但大多数人并没有使用全MVC实现。

    如果你是人,而不是谁,MVC风格patters之一,采用了约的Rails般的变化页面控制器模式,那么你将会被创建用于处理XHR一个单独的控制器。

    If you are one of people, who, instead of MVC-inspired patters, uses Rails-like variation about page controller pattern, then you will be force to create a separate controller for handling XHR.

    在此方案中,没有真正的看法。这是愚蠢的模板替换,而UI逻辑已经在页面控制器被合并。在这种情况下,只有务实的选择是创建一个单独的控制器来处理XHR。

    In this scenario the is no real view. It is replace by dumb template, while UI logic has been merged in the page controller. In this situation the only pragmatic option is to create a separate controller to deal with XHR.

    • 优点:简单的小型项目实施
    • 缺点:可能code重复,难以维持
    • Pros: simpler to implement in small projects
    • Cons: possible code repetition, harder to maintain

    这篇关于好的做法呢? PHP MVC控制器阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆