注册加载器, 对象创建工厂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class RuntimeLoader implements Twig_RuntimeLoaderInterface { public function load($class) { // implement the logic to create an instance of $class // and inject its dependencies // most of the time, it means using your dependency injection container if ('Project_Twig_RuntimeExtension' === $class) { return new $class(new Rot13Provider()); } else { // ... } } } $twig->addRuntimeLoader(new RuntimeLoader()); |
定义扩展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Project_Twig_RuntimeExtension extends Twig_Extension { private $rot13Provider; public function __construct($rot13Provider) { $this->rot13Provider = $rot13Provider; } public function rot13($value) { return $rot13Provider->rot13($value); } } class Project_Twig_Extension extends Twig_Extension { public function getFunctions() { return array( new Twig_SimpleFunction('rot13', array('Project_Twig_RuntimeExtension', 'rot13')), // or new Twig_SimpleFunction('rot13', 'Project_Twig_RuntimeExtension::rot13'), ); } } |