开发者

Should I merge my create and update controllers?

My controllers for updating and creating an object are fairly similar - they both do the same form validation and redirect. But they do, of course, call different methods in the model. Should I merge them or keep them separate? Or should I just make a separate helper function for the validation?

Pros:

  • One controller in开发者_StackOverflow中文版stead of two
  • No duplication of validation code
  • The view (which I did merge) can always point to the same controller

Cons:

  • The merged controller is messier - there are a couple places where I have to check whether it's an update or a create.


I almost always merge them. Same validation, same front end page pointers, etc. There are a few checks you have to do, but I think they outweigh the downside.

And when it comes time to add fields or modify some logic of the handlers, it is a lot easier to do.


Add and Update are diferent methods for the same controller. Although I'm a big fan of keeping light and clever code, at the end of the day, mixing stuff is more a trouble than a solution.

I suppose it depends on the complexity of the form you're submitting. When you have to validate image replacements, for example, it can be a pain.

MVC is about keeping things small and simple, right? Why mix it up?


How about creating a validation method that is passed a variable that would denote the mode (add or update) and have it call the corresponding controller after validation?


I would not merge the two controllers (I like to have some uniformity there), to be DRY (that it is indeed important) and to keep controllers' method skinny I would rather create a method for the common validation.


Update and insert are two different things.

Update will return the number of rows affected and insert will return the id of that insert. that's important since you should be checking if the update or insert actually happened before returning to the controller function.

I should add that validation isn't affected. You call the validation function regardless of an insert or update. If the validation fails you redisplay the form. If it succeeds you do your update or insert.


I wouldn't have a different controller, only different methods in the same controller.

A Controller would be "blog.php" then update is one method and insert is another.

For example:

blog/add
blog/update/1

This way you can set validation in the controller properties and use it just the once.

You can even use the same form if you create a $data['blog'] array based on post or pulled from the db. That might be a step too far, but it makes sense in some situations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜