
Originally Posted by
GOPalmer
TomB, why is this? Surely you'd what to allow view switching at runtime?
Not really, to switch the view you'd switch the controller. How can a view work without its controller?
Otherwise, each controller action needs to specify which view it's going to use. By making the relationship 1:1 this only needs to be defined once.
Now, I have no idea how your own system works but it's common in some "MVC" frameworks to do things like this:
(for ease I'm assuming a 1:1:1 relationship for these examples )
PHP Code:
class UserController extends Controller {
public function showList() {
$users = $this->model->findAll();
$this->set('users', $users);
$this->render('list.tpl');
}
public function sortList($order) {
$users = $this->model->setSort($order);
$this->set('users', $users);
$this->render('list.tpl');
}
public function edit($id) {
$user = $this->model->findById($id);
$this->set('user', $user);
$this->render('form.tpl');
}
public function save() {
if ($this->model->save($_POST)) {
$this->render('success.tpl');
}
else {
$user = $this->model->findById($_POST['id']);
$this->set('user', $_POST);
$this->render('form.tpl');
}
}
}
Which is backwards. This controller has two responsibilities: editing and listing users, causing unecessary repeated code.
Isn't this better:
PHP Code:
class UserListView extends View {
public $template = 'list.tpl';
public function render() {
$this->set('users', $this->model->findAll());
}
}
class UserListController extends Controller {
public $view = 'UserList';
public function sort($order){
$this->model->setSort($order);
}
}
class UserEditView extends View {
public $template = 'form.tpl';
public function render() {
if ($this->model->isSaved()) {
$user = $this->model->getUser();
$this->set('user', $user);
}
else $this->template = 'success.tpl';
}
}
class UserEditController extends Controller {
public $view = 'UserEdit';
public function main($id) {
$this->model->id = $id;
}
public function save() {
$this->model->save($_POST);
}
}
Now, any controller actions which are added relate to a single view meaning they don't have to specify which view they're going to use
and reduces the need for 'default' controller actions which take no parameters.
Bookmarks