phpmustache.php

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


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)


Solution

  • 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.