我应该从 MVC 框架中的控制器或模型中调用 redirect() 吗?
我正在使用 MVC PHP 框架 Codeigniter,并且我有一个直接的问题,即从哪里调用redirect():控制器还是模型?
场景:
用户导航到 www.example.com/item/555。在我的模型中,我在项目数据库中搜索 ID 为 555 的项目。如果找到该项目,我会将结果返回给我的控制器。但是,如果找不到某个项目,我想将用户重定向到某个地方。对redirect() 的调用应该来自模型内部还是控制器内部?为什么?
I'm using the MVC PHP framework Codeigniter and I have a straight forward question about where to call redirect() from: Controller or Model?
Scenario:
A user navigates to www.example.com/item/555. In my Model I search the item database for an item with the ID of 555. If I find the item, I'll return the result to my controller. However, if an item is not found, I want to redirect the user somewhere. Should this call to redirect() come from inside the model or the controller? Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你的模型应该返回 false,你应该像这样检查你的控制器:
并且在你的控制器中执行以下操作:
模型仅用于数据,或者返回标准结果,例如键/值对象或布尔值。
所有逻辑都应由控制器处理/控制。
模型不是特定于页面的,并且在整个应用程序中全局使用,因此如果另一个类/方法使用该模型,它可能会重定向到不正确的位置位置作为您网站的不同部分。
No your model should return false and you should check in your controller like so:
and within your controller do:
Models are for data only either return a standard result such as an key/value object or a boolean.
all logic should be handled / controlled by the Controller.
Models are not page specific, and are used globally throughout the whole application, so if another class / method uses the model, it might get redirect to the incorrect location as its a different part of your site.
控制器似乎是调用重定向的最佳位置,因为控制器通常将调用委托给模型、视图,或者在您的情况下,委托给另一个控制器。
但是,您应该使用对您的应用程序最有意义以及将来更容易维护的任何内容,但也要考虑规则确实存在是有原因的。
简而言之,如果同事试图修复您代码中的错误,“合理的人”标准会说什么?他们中的大多数人最有可能在哪里寻找您的重定向?
另外,你说你已经将结果返回到你的控制器......也许这就是你应该进行重定向的地方......
It seems like the controller would be the best place to invoke your redirect because the controller typically delegates calls to the model, view, or in your case, another controller.
However, you should use whatever makes the most sense for your application and for what will be easier to maintain in the future, but also consider that rules do exist for a reason.
In short, if a coworker were to try to fix a bug in your code, what would the "reasonable person" standard say? Where would most of them be most likely to look for your redirect?
Plus, you said you're returning the result to your controller already... perhaps that's where you should make your redirect...