I have been reading an article for many times and yet, I can't still understand some parts. Link for the article : Model-View-Confusion part 1: Why the model is accessed by the view in MVC
The code below is the one I think I am confused on.
class ListView extends View {
public $model;
public $template;
public $listTemplate;
public $errorTemplate;
public $itemName = 'items';
public function output() {
$result = $this->model->findAll();
if (count($result) > 0) {
$this->template = $this->getTemplate($this->listTemplate);
$this->template->addSet($this->itemName, $result);
} else {
$this->template = $this->getTemplate($this->errorTemplate);
}
return $this->template->render();
}
}
And the controller looks like this :
class UserController extends Controller {
public $viewName = 'ListView';
public function showList() {
$this->view->model = $this->model->user;
$this->view->listTemplate = 'UserList.tpl';
$this->view->errorTemplate = 'ErrorNoUsers.tpl';
}
}
As I can understand the template
was assigned to a result of a method inherited from the View
named getTemplate
passed with a method from the View
again named listTemplate
like this $this->getTemplate($this->listTemplate)
What I am confused on is that the $template
suddenly had a method, which means it becomes a class . right here $this->template->addSet($this->itemName, $result);
and `$this->template->render();
Do you have any idea what happened right there?
Firstly, full disclosure: I'm the author of that article.
It wasn't intended to be a complete code solution but an example of the benefits of applying a full MVC separation of concerns instead of the PAC pattern which is claimed to be MVC by most of the PHP community. How it works behind the scenes is beyond the scope of the article. However, what it was supposed to be demonstrating is that the View should encapsulate the template. In that example the template object could be a Smarty Template, a Twig instance or anything.
In hindsight I shouldn't have named the variables which reference file names "template". The confusion you have is understandable: $this->listTemplate; is a reference to the file containing the template code, and $this->template; is an instance of a template object (could be smarty, twig, anything else) that loads the file referenced in listTemplate.
I'll have a look at amending it to be clearer. I wrote that two years ago and there's several things I'd word differently and explain slightly better in the examples if I wrote it again.