Template Class, with support for binding object contexts to the template.
Requires PHP 5.4 for Closure $this support
Put this in a file named composer.json
:
{
"repositories": [
{"type": "vcs", "url": "git://gist.github.com/1121233.git"}
],
"require": {
"chh/simple-template": "*"
}
}
Get Composer and install:
wget http://getcomposer.org/composer.phar
php composer.phar install
Hello World <?= $name ?>
Here is the output of some method: <?= $this->foo() ?>
Here is the value of a context property: <?= $this->bar ?>
<?php
require "Template.php";
use CHH\Template;
class Context
{
var $bar = "Some Context Property";
function foo()
{
return "Context::foo()";
}
}
$template = new Template('/hello_world.phtml');
echo $template->render(new Context, ['name' => 'Jim']);
This yields:
Hello World Jim
Here is the output of some method: Context::foo()
Here is the value of a context property: Some Context Property
You're right, that should be avoided.
Actually it doesn't have any access to the
$bar
property. I've messed up with the example code.I've checked it with
5.4.0beta2
and they now changed the default scoping behaviour ofbindTo
, so closures don't have access toprotected
andprivate
class members by default. Actually if you try the example it throws an fatal error, with the reason that the protected property$bar
could not be accessed.So I've fixed the example code by making the
bar
property public.Thanks for pointing this out!