在控制器中处理表单提交的最佳实践
举例来说,我正在创建一家网上商店。我有一个名为 products 的控制器,在该控制器中我有一个名为 create_product 的函数。 Create_product 调用一个视图,该视图显示一个表单,用户可以在其中将新产品输入数据库。
当用户填写表单来创建产品时,我是否应该将操作发送回 create_product 控制器并使用 IF 语句进行处理?或卸载到另一个功能?
示例
<form method="post" action="www.example.dev/products/create_product/add">
//the above form would post back to the original controller
function create_product()
{
if(uri->segment(3) == "add")
{
//call a model to do all the database stuff
}
load->view->create_product_form;
}
这是处理此问题的最佳方法还是我应该将其传递给另一个函数?
Lets say for example I am creating a an online shop. I have a controller called products and within that controller I have a function called create_product. Create_product calls a view that displays a form where users get to enter new products into the database.
When the user fills in the form to create a product, should I send the action back to the create_product controller and handle it with an IF statement? or offload to another function?
Example
<form method="post" action="www.example.dev/products/create_product/add">
//the above form would post back to the original controller
function create_product()
{
if(uri->segment(3) == "add")
{
//call a model to do all the database stuff
}
load->view->create_product_form;
}
Is this the best way to handle this or should I be passing it off to another function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要在一个函数中塞入大量内容,使用 URI 段来过滤它。 createProduct() 可以列出可用于创建的产品(我假设采用 CRUD 格式),并且表单的提交应使用 POST 数据对另一个控制器执行 ping 操作。也许是 insertProduct(),其中数据被清理并发送到模型以插入到数据库中。
关注点分离!使函数尽可能独立,并为函数名称提供良好的描述符。
Don't cram a ton of stuff in one function using the URI segment to filter it. createProduct() can list the products available for creation (in a CRUD format, I assume), and the submission of the form should ping another controller with the POSTed data. Perhaps insertProduct(), where the data is sanitized and sent to the model for insertion to the database.
Separation of concerns! Keep the functions as separate as possible with good descriptors for the names of the functions.
我(个人)将有一个函数来设置表单参数并使用该表单“启动”视图,另一个函数用于验证和调用模型以将该表单的值放入数据库中。我相信这确实取决于您,但是如果您根据控制器的实际功能将控制器划分为多个功能,那么代码会更清晰。
I (personally) would have a function that set the form parameters and "launch" the view with that form, and another function used to validate and call the model to put the values of that form into the database. I believe that is really up to you, but the code would be cleaner if you divide the controller with several functions depending on what they actually do.
我喜欢 symfony 处理表单和表单的方式。表单提交。它是一个函数(动作)的
简化代码:
I like the way symfony deals with forms & form submission. It is in one function (action)
simplified code: