2

So I'm writing my MVC and need to display my views.

It's pretty simple at the moment, just wrapped in a function inside my main controller.

ob_start();
require_once('views/' . $fileName . '.php');
$output = ob_get_contents();
ob_end_flush();
return $output;

However, I don't quite understand how to set all the variables within the view I am rendering, and this is the most important part (no shit).

Any tips in regards to doing this? And any code samples you want to share in regards to a basic MVC framework?

I'm writing the most basic thing I could think of, with just a few controllers, models, views, an autoloader, and a index.php to route all the requests. I'm not interested in rewriting using IIS rewrite module, so I'm just running _GET to fetch the query string.

Thanks in advance, you people are always a great help.

ruleboy21
  • 5,510
  • 4
  • 17
  • 34
Nict
  • 3,066
  • 5
  • 26
  • 41
  • Please see http://codeangel.org/articles/simple-php-template-engine.html ... also, do not confuse views with templates ([this](http://stackoverflow.com/a/16596704/727208) might help). – tereško Nov 22 '13 at 00:18

1 Answers1

3

This is a rough idea (code taken and modified from one of my own frameworks, I built a long ago, only to clarify my understanding), you may create a View class and put this function as method, but this function could be used as

$content = render('view_name', array('name' => 'Heera', 'age' => '101'));

Function render() :

function render( $filename, $data = array() )
{
    extract($data, EXTR_SKIP);
    ob_start();
    include "views/$filename.php";
    return ob_get_clean();
}

You can think of a view like this

<div><?= htmlspecialchars($name) ?></div>
<div><?= htmlspecialchars($age) ?></div>

You can follow some existing frameworks to (I did when I developed this one and helped me a lot) and write your own.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 2
    Thanks, I did something very similar, only I put the render function in the top-parent controller, I believe I'll rewrite it to use a view class as it would be a better way to differentiate the concerns. Thanks for your answer, really helpful :) – Nict Nov 16 '13 at 14:15