Tuesday 14 September 2010 4:41:06 am
While developing templates, you might have noticed that you can access most of every kernel objects attributes directly in templates :
{* $myNode will hold an eZContentObjectTreeNode object *} {def $myNode = fetch( 'content', 'node', hash( 'node_id', 2 ) )} {* Directly access to $myNode attributes *} NodeID : {$myNode.node_id}<br /> Name : {$myNode.name} {* Inspect $myNode *} {$myNode|attribute( 'show', 2 )}
In order to be able to use a PHP object in templates such as eZContentObjectTreeNode in the example above, you will need to implement 3 methods :
So, when you need to access an object attribute, eZ Publish first checks if it does exist via hasAttribute() method. If so, then it will use attribute() accessor to retrieve the value. Last attributes() method is only used when inspecting the object with attribute template operator.
Example :
<?php class MyExampleClass { /** * Attribute holder * @var array */ private $attributes; public function __construct() { $this->attributes = array( 'first_attribute' => 'foo', 'another_attribute' => 'bar' ); } /** * Checks if $attributeName is a valid attribute * @return bool */ public function hasAttribute( $attributeName ) { return isset( $this->attributes[$attributeName] ); } /** * Attribute accessor * @return mixed */ public function attribute( $attributeName ) { return $this->attributes[$attributeName]; } /** * Returns all available attribute names * @return array */ public function attributes() { return array_keys( $this->attributes ); } }
Template code :
{* Assume that $myObject is a MyExampleClass object *} {$myObject.first_attribute}{* Will display 'foo' *}<br /> {$myObject.another_attribute}{* Will display 'bar' *} {* Inspect $myNode *} {$myNode|attribute( 'show', 2 )}