fabpot/Twig — Issue #506: Inability to access custom properties
Author: suhana
Created: 2011-11-07 14:15:54+00:00
State: open

I'm not sure how to explain this fully, but it has become a nasty stumbling block for me; that is the inablity to access special properties that are only available via the __get() magic method.

I have been using a simplified model that only fetchs data if and when it is needed - (see below for an example). As it stands, Twig is unable to see the properties normally accessed in this way as uses Reflection to examine the class directly.

With small models, this is not a problem, however the largel models accesing tables with many fields and deep references to other tables this becomes a task I cannot see how to elegantly overcome using Twig in its current form.

```php
id = $id;
}

public function __get( $key )
{
if (is_null($_data))
{
// data hase not yet been loaded,
// load from the database

$rs = mysql_query('SELECT * FROM users WHERE id = ' . $this->id);
$row = mysql_fetch_array($rs, MYSQL_ASSOC);

$this->data = $row;

mysql_free_result($rs);
}

// check for calculated fields and
// special fields returning objects

switch ($key)
{
case 'age':
return time() - $this->data['born'];

case 'partner':
// Lazy loading of partner only occurss *if* the
// calling process actually needs access to it.
if ($this->data['partner'])
return User::instance($this->data['partner'];
return null;
}

if (array_key_exists($key, $this->data))
return $this->data[$key];

throw new Exception('Property "' . $key . '" not found');
}
}

$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
$user = User::instance(1);
$html = <<

ID

{{ user.name }}

Name

{{ user.name }}

EOF;
echo $twig->render
(
$html,
array
(
'user' => $user
)
);

/**
* Ideal Result
* ============
*

*
ID

*
1

*
Name

*
Susan

*

*
*
* Actual Result
* =============
*

*
ID

*

*
Name

*

*

**/
```