views:

52

answers:

3

I'm trying to wrap my head around the best way to do a templating system for my PHP CMS. I'm a little stuck and so I'm looking for a few suggestions or ideas. Here is my desired setup:

Each page is composed of various widgets (or content blocks, if you prefer). Each widget has an MVC architecture, with the View being simple, composed of mainly HTML with a little PHP. The Widget Controller will pass info from the Model to populate the View.

So far, so good. Here's the catch: Rather than just including the Widget View file onto the page, I'd like to have the View in string format. I can do that, but my current solutions lose some of the cleanness and simplicity of the MVC approach as the Model and View tend to get combined.

I might be asking for the moon here, but I thought I would ask for ideas in case I'm missing something blatantly obvious. Is there a way that I can keep a simple View, be able to populate it, execute any statements and loops, and keep the result as a string? I'd like to keep it as simple as possible and would like to avoid some large regex parsing solution.

Please note that I'm looking for a general approach or code examples, but I'm not looking for an existing templating system to integrate. If you need clarification on anything, just add a comment and I'll update the question.

+3  A: 

Use ob_start() before you include the view script, and ob_get_contents() afterwards.

Bill Karwin
Aha, I *was* missing something blatantly obvious. Thanks Bill!
VirtuosiMedia
A: 

Have a look at Smarty. You can absolutely separate the views and include the widgets' templates into pages' templates and so on.

EDIT: Ok, i didn't see the "i don't want existing system", so what about you create some variable registry and each time you want to pass a variable to your templating system, you call something like VariableRegistry::assign('variable_name', $value). I'm using something like it (integrated with Smarty on http responses). The good thing about this is that you can serialize all your passed variables to json, xml etc., that comes in handy for Ajax and REST api later :-)

cypher
+1  A: 

Use output buffering and the benefit of function scoping:

Something like:

class View {
   var $params;
   function get_view_template($file_path) {
      extract($this->params);
      ob_start();
      include $file_path;
      $string = ob_get_contents();
      ob_end_clean();
      return $string;
   }
}
Trent Davies