I’m building my own MVC framework and have encountered a problem when sending variables into views. The loadView() looks like this:
function loadView($view, $variables = array())
{
$file_path = APPLICATION_PATH . 'views/' . $view;
if (file_exists($file_path))
{
if (is_readable($file_path))
{
if (! empty($variables)) extract($variables);
include($file_path);
}
else
{
throw new Exception('Could not read view from ' . $file_path);
}
}
else
{
throw new Exception('Could not load view from ' . $file_path);
}
}
It works just as expected. However, when I’m setting up a template view like this things get weird:
loadView('layout/header.php');
loadView($view);
loadView('layout/footer.php');
It’s called like this ($user is an object):
$data['view'] = 'login/showUser.php';
$data['user'] = $user;
loadView('layout/template.php', $data);
The $view variable gets set in the template file and loads the correct view. However, the $user variable is unable to travel into the dynamically loaded view which only contains this code:
<p>User ID: <?php echo $user->id; ?></p>
I can do this in CodeIgniter and I find it a little weird since when the $view and $user variables are extracted in the first loadView() call to the template, they should be available to the next view which is simply included into the scope.
What did I overlook?
Each loadView() call has its own local scope, which are not shared between different invocations of loadView(). In CodeIgniter, this likely works because its view renderer stores the variables in some static storage. You need to pass all variables you need in each view explicitly, or you need to add static storage to loadView(), like this: