开发者

How does Symfony pass members set in an action to a template?

开发者 https://www.devze.com 2022-12-27 23:36 出处:网络
How does a member set inside an action... $this->foo = \'bar\'; ...become a variable accessible from a template...开发者_如何学JAVA

How does a member set inside an action...

$this->foo = 'bar';

...become a variable accessible from a template...开发者_如何学JAVA

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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消