该代码应该位于 MVC 结构中的什么位置?
我读了很多书,得到的结果好坏参半。
说我有这样的代码?
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(strlen($name) > 0 & strlen($email) > 0)
{
$u = new User();
$u.name = $name;
$u.email = $email;
$u.validate();
}
这段代码应该放在哪里?实际检查表单以确保其具有实际值的代码?我说的是模型,但是如果您的表单跨越多个模型怎么办?
我有点困惑,任何帮助解决它的帮助将不胜感激。
I'm reading a lot and getting really mixed results.
Say I have code like this?
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(strlen($name) > 0 & strlen($email) > 0)
{
$u = new User();
$u.name = $name;
$u.email = $email;
$u.validate();
}
Where should this code live? The code that actually checks the form to make sure it has actual values? I say Model, but then what if your form spans across multiple models?
I'm a bit confused and any help to clear it up would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
理想情况下,完全分离关注点:
Controller
应该收集$_POST
数组并将其传递给Model
。然后模型将进行修剪和验证等处理。
我会+1模型包含业务逻辑。
Ideally for the complete separation of concerns:
The
Controller
should be collecting the$_POST
array and passing it to theModel
.Then the
model
would do the processing such as trim and validating.I would +1 that the Model contains business logic.
模型层的检查应保证数据库的完整性。所有这些检查都应该存在于您的 u.validate() 方法中。
您还可以向控制器层添加检查作为优化或驱动某些视图操作。
我会这样重构。
控制器代码
型号代码
the checks in the model layer should guarantee database integrity. all those checks should live in your u.validate() method.
you may additionally add checks to your controller layer as an optimization or to drive some view action.
i would refactor this way.
controller code
model code
将其放入
model
部分,因为模型包含业务逻辑。.参考
Put this into
model
section, because model contains business logics..Reference
这是一篇很棒的文章,深入解释了 PHP 中的 MVC
Oreilly 上面的答案是正确的,但是为了让你真正使用 MVC需要对每个部分为何会到达其所在位置有一定程度的了解,希望本文能将您推向正确的方向。
This is a great article that goes far to explaining MVC within PHP
Oreilly the answers above are correct but in order for you to truly use MVC a certain amount of understanding about why each part goes where it goes is required hopefully this article will push you in the right direction.
如果您在保存之前验证数据(例如电子邮件、姓名),那么我会投票给 Model。
您的 MVC 框架应该能够验证每个模型的数据。
归根结底,MVC 是一种架构。没有明确的模式。所以这取决于你。很多时候一致性会胜出。也就是说,如果您想将其放入控制器而不是模型中,请在整个代码中执行此操作。
If you are validating data before saving (e.g. email, name), then I vote Model.
Your MVC framework should be able to validate each Model's data.
In the end, MVC is an architecture. There is no definitive pattern. So it's up to you. A lot of the time consistency wins out. That is to say, if you want to put it in the controller instead of the model, do it throughout your code.