views:

200

answers:

2

Is there any way I can pre-process a PHP view script without using a particular MVC framework?

Basically I want to render the view and pass it as an HTML string to another view. The view I'm trying to render has some references like $this->rows, and, of course, I would need to add the values of those references to the script before generating the HTML.

Is this possible?

A: 

The way to do it depends on the framework you're using.

But this can be done with PHP by just using nested includes.

For example

page.php

<?php include(HEADER) ?>

<?= $var ?>

<?php include(FOOTER) ?>

All variables available to page.php will be available to the header and footer views as well.

Galen
I'm using Joomla. The problem is I need to pre-process page.php and turn it into a string. And I need to change the value of $var before I do that. So, if the file were an object, I would want something like this: page.php->var = "foo" - and then get render the page into a string with the assigned values.
Tony
+2  A: 

Yes it is completely possible. You'll want to utilize output buffering to ensure the initial view isn't displayed and then store that views output in a variable.

ob_start();
include ('/path/to/file.php');
$contents = ob_get_contents();
ob_end_clean();
cballou
But how would I add data to the included file before rendering it? The included view file has references like $this->rows that I want to change.
Tony
I guess I can add the variables to my context before I include my view - but for some reason ob_end_clean() is not "silently discarding my buffer contents." As soon as I include by view file it is sent to output, whether it's in the buffer or outside.
Tony
Well, correction, ob_end_clean() does silently discard my buffer contents if the contents are not an include - but the include outputs regardless. Any way to prevent that?
Tony
Found the problem! The buffer wont stop a fatal error from puking everything to output!
Tony
Good find Tony, glad you seem to have resolved your problem.
cballou
Everything is working perfectly - beautiful - this is a huge discovery for me. Thanks so much!
Tony