Pergunta

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 witihin 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.

Foi útil?

Solução

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() )
{
    try {

        $file = 'views/' . $filename. '.php';
        if( !is_readable($file) ){
            throw new Exception("View $file not found!", 1);
        }

        $content = file_get_contents( $file );
        ob_start() && extract($data, EXTR_SKIP);
        eval('?>'.$content);
        $content = ob_get_clean();
        ob_flush();
        return $content;

    } catch (Exception $e) {
        return $e->getMessage();
    }
}

You can think of a view like this

<div><?php echo $name ?></div>
<div><?php echo $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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top