The $_account
that you are trying to access is a variable in the function scope of your template::load
method, the $_account
that you initialized is a global variable.
If you want to use a global variable you should either declare it with global $_account
within the function or use $GLOBALS['_account']
.
A simple template example (the rest is copied from your source):
Template.class.php:
interface IApiHandler {
public function printContent();
}
SomeTemplate.class.php:
class SomeTemplate implements Template {
public function printContent() {
$account = Account::getCurrent();
?>
<div id="header">
<?php if($account->is_loggedin() == true): ?>
<p>logged in</p>
<?php else: ?>
<p>not logged in</p>
<?php endif;
}
}
Account.class.php:
class Account {
private static $current = null;
public static function getCurrent() {
if(self::$current === null) {
self::$current = new Account();
}
return self::$current;
}
public function __construct() {
//account init...
}
public function isLoggedIn() {
return rand()%2;
}
}
defaults.php:
session_start();
// define path settings
// connect to database, memcache
// lots of other stuff....
//autoloader for functions
spl_autoload_register(function ($class) {
if (file_exists(CLASS_PATH.DS.$class.'.class.php'))
{
include CLASS_PATH.DS.$class.'.class.php';
}
});
$headerTemplate = new HeaderTemplate();//not included in the example...
$bodyTemplate = new SomeTemplate();
index.php
<php require 'defaults.php'; ?>
<html>
<head>
...
</head>
<body>
<?php $headerTemplate->printContent(); ?>
<?php $bodyTemplate->printContent(); ?>
</body>
It should also be noted that this is missing the C from MVC. It is only an example of how to make templates as classes.
Usually the index (or in this case default.php) only needs to decide which controller is suppose to handle the request. The controller then has to decide (or default to) which template should be used (if any).
Also it is better if all the html is contained in the templates, no output should be printed before the controller handles the request.