I’d like to know how to properly create controllers and actions in MVC. So far I’ve used them in implementations that were not true MVC so I may not have a correct understanding about when I should create a new controller and when a new action - I’d like to learn some proper basics.
Let’s say I have some common tasks with managing users:
- Add user
- Edit user
- List users
- Delete users, hide/unhide users (toggle a flag on or off)
- Display single user data
Below I’m presenting my suggested scenarios, please comment on each one whether it looks good on not:
Pt. 1 & 2: adding and editing a user are almost identical in html display (same form) so I suspect these will require one controller with two actions. One controller because one controller is always tied to one view. Additionally, I think I will need submit actions that will get values submitted by POST and either redirect to another page or redisplay the form in case of a validation error. So I end up with 4 actions:
class UserFormController {
public function add() {
// ...
}
public function edit() {
// ...
}
public function addSubmit() {
// ...
}
public function editSubmit() {
// ...
}
}
Pt. 3: Listing users - there will be features like listing all users, filtering by criteria and pagination. I suspect I can get away with 1 controller with 1 action and simply pass all the necessary parameters from GET to the model in the action.
Pt. 4:: Deleting (selected) users, hiding/unhiding users - this is supposed to delete the users or perform some other operation in the db on the user and redirect back to the user list. Do I need the view at all in this case? I suppose I can create one controller with 3 actions:
class UserChangeController {
public function delete() {
// ...
}
public function hide() {
// ...
}
public function show() {
// ...
}
}
What do I do about the view then? Do I create an empty one or allow my system to have viewless controllers? I’m a little baffled with this one - do I use these actions to pass POST criteria to specific methods in the model that will perform the requested updates on the users in the db? Like this:
class UserChangeController {
public function delete() {
$userIds = array_keys($_POST['checkboxes']);
$this->model->deleteUsers($userIds);
// I don't know if this is the best place to do redirection?
header("Location: " . $_POST['redirect']);
exit;
}
}
Pt. 5:: a page which displays user info - this should be easy, 1 controller and 1 action.