From c5072c8a9e908b95b1467b37e4760eee0ca807a7 Mon Sep 17 00:00:00 2001 From: fabien Date: Thu, 5 Nov 2009 17:42:55 +0000 Subject: [PATCH] added a tip about dynamic properties git-svn-id: http://svn.twig-project.org/trunk@114 93ef8e89-cb99-4229-a87c-7fa0fa45744b --- doc/02-Twig-for-Template-Designers.markdown | 1 + doc/06-Recipes.markdown | 34 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 0 deletions(-) diff --git a/doc/02-Twig-for-Template-Designers.markdown b/doc/02-Twig-for-Template-Designers.markdown index 6ae9b3c..544f8d4 100644 --- a/doc/02-Twig-for-Template-Designers.markdown +++ b/doc/02-Twig-for-Template-Designers.markdown @@ -70,6 +70,7 @@ If a variable or attribute does not exist you will get back a `null` value. >the PHP layer: > > * check if `foo` is an array and `bar` a valid element; +> * if not, and if `foo` is an object, check that `bar` is a valid property; > * if not, and if `foo` is an object, check that `bar` is a valid method; > * if not, and if `foo` is an object, check that `getBar` is a valid method; > * if not, return a `null` value. diff --git a/doc/06-Recipes.markdown b/doc/06-Recipes.markdown index 0acd3f1..f1812d6 100644 --- a/doc/06-Recipes.markdown +++ b/doc/06-Recipes.markdown @@ -100,3 +100,37 @@ syntax: 'tag_block' => array('{', '}'), 'tag_variable' => array('{$', '}'), )); + +Using dynamic Object Properties +------------------------------- + +When Twig encounters a variable like `article.title`, it tries to find a +`title` public property in the `article` object. + +It also works if the property does not exist but is rather defined dynamically +thanks to the magic `__get()` method; you just need to also implement the +`__isset()` magic method like shown in the following snippet of code: + + [php] + class Article + { + public function __get($name) + { + if ('title' == $name) + { + return 'The title'; + } + + // throw some kind of error + } + + public function __isset($name) + { + if ('title' == $name) + { + return true; + } + + return false; + } + } -- 1.7.2.5