I have an application built using an MVC framework (for argument's sake, PHP/Yii2) and have a question regarding where to carry out logic and generate values which will be injected into, for example, IndexView
or AboutUsView
.
In this instance the 'About Us' page is displayed when the route /about-us
is hit by a browser, calling the actionAboutUs
method in SiteController
which simply calls the method Controller::render($template)
causing the $template
php file to be parsed and output.
This is fine when the content of $template
is not dynamic in any way; just static html content. However when there should be dynamic content my understanding of MVC is that this should be computed in the controller and passed to the render
method.
To be truly MVC is this correct and if so a hard and fast rule?
For example, in a page I'd like to output the number of posts which a class method Post::getNumberPosts()
could be called in the view directly and output or called in the controller, assigned to a variable, the variable injected in to the view and the value of the variable output. Does the first method go against MVC as a pattern?
Or if on the homepage I'd like to output one of two different messages depending on the logged in status of the current user. If the user is not logged in a generic welcome message or if they are logged in, call other methods to generate user specific content. At the moment this is being handled in the view in the following manner
<?php if (!App::loggedIn) { ?>
<p>Generic Welcome!</p>
<?php } else {
$myVar = currentUser->getDetails();
?>
<p>hello <?php echo $myVar->myName;?></p>
<?php } ?>
Could this case be handled in a more MVC manner?
tl;dr All logic in controller and pass to view?