I have a class which contains a method to load a view. This works perfect and the page is loaded correctly! The problem I'm having is that I can't seem to figure out a way to pass variables to the view that my method currently tries to load. How can I go by passing variables to the page? Is there a way I can manipulate my current code to make this work? Or am I going in the complete opposite direction?
Controller Class:
<?php
class Controller {
private $args = array();
public function view($page, $args = null) {
if ($args !== null) {
$this->args = $args;
extract($this->args);
}
$page = VIEWS . $page . '.php';
$template = $this->getTemplate($page);
echo $template;
}
private function getTemplate($file) {
ob_start();
include($file);
$template = ob_get_contents();
ob_end_clean();
return $template;
}
}
?>
Controller:
<?php
class Page extends Controller {
public function person($age) {
$data['age'] = $age;
$this->view('person', $data);
}
}
?>
View Contents:
</h1>My name is Dennis. My age is: <?php echo $age; ?></h1>
The end result is an undefined variable ($age).
The variables which you extract in view()
are not available in getTemplate()
. It is a different scope. You should instead extract them in the same method that does the rendering.
Also, what you have there is not an MVC view. It's just a template. A view in MVC is an instance which is responsible for UI logic. It should be requesting the information, that it needs, from model layer and then, if a response is not simply a HTTP location header, creating the HTML using multiple templates.
Try this:
</h1>My name is Dennis. My age is: <?php echo $data['age']; ?></h1>
You extract the variables in a different method than where you include the template. If you want to use plain variables in your templates, make sure that they are extracted in the same scope.
The easiest way is to pass down the $args variable to getTemplate, and do the extract method in the getTemplate method
private function getTemplate($file, $args = null) {
if ($args !== null) {
extract($args);
}
ob_start();
include($file);
$template = ob_get_contents();
ob_end_clean();
return $template;
}
when you include and capture the the output, that php file is executed, so before inclusion all the variables must be present
If you dont want to pass down variables you can use $this->args inside of the template