tags:

views:

93

answers:

3

So I'm working on my own little MVC framework as a learning exercise. It's working great, but I want to be able to reference variables in my view files without $this.

So for example I have a controller object which instantiates a view object. From the controller I pass the variables to the view like this

$this->view->foo = "bar";

Then the view object includes the relevant code for the view (eg: myView.phtml). So to access "foo" in the view file I use this

echo $this->foo;

But what I would like to do, and I don't know if this is possible or wether I'm missing something obvious, but what I would like to do is reference the variables like this

echo $foo;

Without me posting the entire source, can anyone point me in the right direction?

+1  A: 

You could write some code that parses your html view input and automatically modifies your entries from $foo or [foo] to $this->foo.

So you could put something like this in your html view:

<p>[foo]</p>

and then have some view code parse the file and change all instances of [foo] to the value of $this->foo. So your output becomes:

<p>I'm the foo value</p>

Or, you could use something like Smarty - it does this for you and has many other reasons to use it too.

Steve Claridge
good idea. I may be asking too much, but I'm trying to avoid template tags for my own anal reasons. And Smarty is great, but this is all for my own learning benefit so I feel compelled to roll my own solution.
gargantaun
+1  A: 

Have you tried extract? You'll have to add a method to put all your variables into an array. The only real limitation is this makes the variables read only.

jmucchiello
+1  A: 

If you would like every variable in the view object to be availble inside the view, you could add your variables to a property of the view object that is an array and then use extract() to make them available:

$this->view->variables['foo'] = 'bar';

extract($this->view->variables); // now $foo = 'bar';

I'm not a big fan of extract(), but this would accomplish what you are looking for.

jonstjohn