This site has been archived and you can no longer log in or post new messages. For up-to-date community resources please visit ezplatform.com

eZ Community » Learn » eZ Publish » Understanding and developing fetch...

Understanding and developing fetch functions

Tuesday 14 September 2010 1:41:06 pm

  • Currently 5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Appendix

Make a PHP object usable in templates

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 :

  • attribute( $attributeName ) Accessor. Returns value of object attribute which name is $attributeName
  • hasAttribute( $attributeName ) Checks if object attribute $attributeName is available
  • attributes() Lists every available attributes (only names)

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 )}
36 542 Users on board!

Tutorial menu

Printable

Printer Friendly version of the full article on one page with plain styles

Author(s)

Proudly Developed with from