I am trying to program in MVC architecture.
So, I have one HTML form where user can insert, let’s say, a movie. I have one controller for that (for adding that movie) and one view for the HTML form.
But I also want user to be able to edit that movie after he added it. So, he presses a button “Edit a movie” and he’s redirected to the new URL and I have new controller and new view (it has the same form as when user adds the movie, but only now he sees values in inputs which he entered previously, I hope you understand what I mean) for this editing form.
Also, when I want to show how his movie looks like to other users, I once more time have new Controller and new View for that.
edit: I also have to validate what he enters. So, that validations should be in model? Because I validate twice, it doesn’t seem right.
Is it correct thinking of MVC? Or what’s the best approach for making this? Thanks.
You got it almost right, but there is still some place to simplify it. Common thing is to create action functions inside of your controller which handle certain (surprise, surprise) actions user can do. Usually you’d have, for example,
Article controllerwith actionsadd,remove,editetc. This way you centralize actions for common entity of your application and prevent overflow of controllers. It’s easier to maintain, easier to find if you want to change something asap and you will nicely follow DRY principle.Another thing you could do is to create
abstract base controllerfor common stuff that’s used in multiple controllers (dynamic loading of meta data from database comes in mind).Having multiple views is fine. You don’t have much of a choice anyway. But I’d recommend using some templating engine which would make your life easier and once again force you to not repeat yourself. Twig or Smarty would be perfect choice.
Validation logic should be located in model.
Modelis responsible for most of the backend logic (data manipulation, its validation…).Controllersjust take requests, loads appropriate data fromModelsand point you to properView. Don’t get confused though, you usually end up validating yourModelsinsideController(callingvalidate()functions, for example).Anyway, in the end, you’ll find out there are quite many ways how to look at MVC pattern. Some people prefer “fat models” and “skinny controllers”, some the other way around. Use whatever fits your needs and keep it simple!
If you want some studying materials, take a look at Symfony2 framework or CakePHP tutorials. There are some valuable information regarding this topic. Maybe you’ll end up using one of them instead of reinventing the wheel 🙂