マジック メソッドのもう 1 つの便利なアプリケーションは、特に__get
and__set
と__toString
テンプレートです。マジック メソッドを使用する単純なアダプターを作成するだけで、テンプレート エンジンからコードを独立させることができます。別のテンプレート エンジンに移行する場合は、これらのメソッドのみを変更してください。
class View {
public $templateFile;
protected $properties = array();
public function __set($property, $value) {
$this->properties[$property] = $value;
}
public function __get($property) {
return @$this->properties[$property];
}
public function __toString() {
require_once 'smarty/libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->template_dir = 'view';
$smarty->compile_dir = 'smarty/compile';
$smarty->config_dir = 'smarty/config';
$smarty->cache_dir = 'smarty/cache';
foreach ($this->properties as $property => $value) {
$smarty->assign($property, $value);
}
return $smarty->fetch($this->templateFile);
}
}
このアプローチの隠れた利点は、View オブジェクトを別のオブジェクト内にネストできることです。
$index = new View();
$index->templateFile = 'index.tpl';
$topNav = new View();
$topNav->templateFile = 'topNav.tpl';
$index->topNav = $topNav;
ではindex.tpl
、ネスティングは次のようになります。
<html>
<head></head>
<body>
{$topNav}
Welcome to Foobar Corporation.
</body>
</html>
ネストされたすべての View オブジェクトは、すぐにその場で文字列 (正確には HTML) に変換されます。echo $index;