用户输入是否输入到控制器或模型? [英] Does user input go to the controller or model?

查看:70
本文介绍了用户输入是否输入到控制器或模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我将模型拆分开了,但是我的控制器和视图仍然合并在一个12k的行文件中.我一直在为此目的创建一个真正的MVC系统,拆分视图,但是在查找拆分内容时,我注意到我的控制器正在做很多可能属于模型的工作.

Right now I have my model split out, but my controller and views are still combined in a 12k line file. I've been looking to create a true MVC system for this, splitting out the views, but while looking for stuff to split out, I've noticed my controller is doing a lot of work that might belong in a model.

例如,假设我有...

For example, let's say I have...

if (isset($_POST['write'])) {
    $obj = $objManager->get($_POST['id']);
    $obj->setFoo($_POST['foo'])
        ->setBar($_POST['bar']);
    $objManager->write($obj);
    echo ... 
}

...因此,我们知道回显后的内容会进入视图模板.经理是我的模特.所以我的问题是,是否要从$ _POST中读取所有数据并在控制器中设置数据?还是我以某种方式将其放入模型中,像这样...

... so the stuff after echo, we know goes into a view template. The manager is my model. So my question is, do I do all the reading from $_POST and setting up the data in the controller? Or do I somehow put that into the model, like so...

if (isset($_POST['write'])) {
    $objManager->update($_POST);
    echo ...
}

...其中update()基本上执行相同的操作,设置变量并保存内容.

... where update() does basically the same thing, sets the variables and saves the thinger.

推荐答案

您的第一个示例对我来说似乎是更好的解决方案.它将接受用户输入的任务与访问模型中的数据正确地分开.换句话说,该模型并不关心输入来自POST参数的事实.

Your first example looks like the better solution to me. It properly separates the tasks of accepting user input from accessing the data in your model. In other words, the model doesn't care about the fact that the input is coming from POST parameters.

在第二个示例中,您将模型与控制器紧密耦合,因为模型希望将POST参数列表传递给它,以便更新对象.该模型不必关心"id","foo"和"bar"变量的来源.

In the second example, you are tightly coupling the model with the controller because the model expects that a list of POST parameters be passed to it in order to update the object. The model shouldn't have to care about where the "id", "foo", and "bar" variables are coming from.

第二个示例看起来更优雅一些,但是它对单元测试并不友好.为了对其进行单元测试,您必须向其传递一个关联数组,其键与POST参数的名称匹配.在PHP中,这并不是什么大问题,因为所有内容都是动态类型的,但这是您还需要担心的一件事.

The second example looks a little more elegant, but it is not as friendly to unit testing. In order to unit test it, you would have to pass it an associative array, whose keys match the names of the POST parameters. This is not as big of a deal in PHP, since everything is dynamically typed, but it's one extra thing you have to worry about.

这篇关于用户输入是否输入到控制器或模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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