{{title}} {{/entities}} Rendered by: $m = new Mustache_Engine( ['loader' => new Musta" /> {{title}} {{/entities}} Rendered by: $m = new Mustache_Engine( ['loader' => new Musta" /> {{title}} {{/entities}} Rendered by: $m = new Mustache_Engine( ['loader' => new Musta"/>

How to iterate over array of objects with private properties in Mustache properly?

357 Views Asked by At

Example of mustache template:

{{#entites}}
  <a href="{{url}}">{{title}}</a>
{{/entities}}

Rendered by:

$m = new Mustache_Engine(
  ['loader' => new Mustache_Loader_FilesystemLoader('../views')]
);

echo $m->render('index', $data);

Basic nested array.

$data = [
   'entities' => [
       [
         'title' => 'title value',
         'url' => 'url value',
       ] 
    ]
];

This is rendered properly in template.

Array of objects of class:

class Entity 
{
  private $title;

  private $url;

  //setter & getters

  public function __get($name)
  {
      return $this->$name;
  }
}

Mustache argument:

$data = [
   'entities' => [
       $instance1
    ]
];

In this case not working - output is empty (no values from properties)

2

There are 2 best solutions below

0
hassan On BEST ANSWER

You can make a use of ArrayAccess Interface, to be able to access your private properties as follow:

class Foo implements ArrayAccess {
    private $x = 'hello';

    public $y = 'world';

    public function offsetExists ($offset) {}

    public function offsetGet ($offset) {
        return $this->$offset;
    }
    public function offsetSet ($offset, $value) {}
    public function offsetUnset ($offset) {}
}

$a = new Foo;

print_r($a); // Print: hello

Of course this is a trivial example, you need to add more business logic for the rest of the inherited methods.

9
Salvatore Q Zeroastro On

Instead of magic methods, why don't you use a function like this in the class

public function toArray()
{
    $vars = [];
    foreach($this as $varName => $varValue) {
        $vars[$varName] = $varValue;
    }

    return $vars;
}

then call that function to grab the variables as array

$data = [
   'entities' => $instance1->toArray()
];