tags:

views:

41

answers:

1

How does a member set inside an action...

$this->foo = 'bar';

...become a variable accessible from a template...

echo $foo; // bar

I would like to know how it is achieved at a framework level.

There is a lot of documentation on how to use Symfony, but I've not managed to find much about how it all fits together behind the scenes (class structure/inheritance etc).

Thanks in advance for your help!

+3  A: 

The general model is this:

The controller implements __set() which adds the variables to the View:

class Controller {
  .. snip ..
  public function __set($key, $value) {
    $this->_view->addVar($key, $value);
  }
  .. snip ..
}

The view uses extract() (or other suitable approach such as variable-variables) to create in-scope variables from those values:

class View {
  private $_vars = array();
  private $_templatePath;
  public function __construct($templatePath) {
    $this->_templatePath = $templatePath;
  }
  public function addVar($key, $value) {
    $this->_vars[$key] = $value;
  }
  public function render() {
    extract($this->_vars);
    include $this->_templatePath;
  }
}

Because of the way PHP handles scope, the template has access to the variables created by the view's render() method.

d11wtq
Excellent, thanks very much!
Martin Chatterton
I should mention that I disagree with the approach taken by symfony here too. It would be much clearer (and since you asked this indicates my point) if the API implemented made you just say: $this->_view->addVar($name, $value);The property is not one of the controller; it belongs to the view.
d11wtq
That's really great, thank you.
Martin Sikora