Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom MVC, how to implement a render function for the controller so the View can access variables set by the Controller

I'm adding new features to an existing code base. Anyway, the current feature I'm doing should be in MVC in my opinion. The existing code base isn't MVC but the feature I'm implementing, I want it to be MVC. And I don't want to roll some existing MVC into the existing codes.

So, my problem is... I don't know to implement a render function for the controller class. Usually, in MVC you have the controller do some stuff, set it to a variable using a render function, and the View can now magically access that given variable set by the controller.

I have no idea how to do this other than global, which just feel wrong, I keep on telling myself there has to be a better way. Edit: It's global isn't it? >_> How does those other frameworks do it?

Here's a silly example:

Controller:

class UserController extend BaseController 
{
public function actionIndex() 
{
  $User = new User; // create a instance User model

  $User->getListofUser();

  $this->render('ListOfUser', 'model'=>$model);
}
}

View:

<?php
//I can use $ListOfUser now...
//some for loop
echo $ListofUser[$i];
?>

Thank you in advance!

like image 327
mythicalprogrammer Avatar asked Nov 16 '10 06:11

mythicalprogrammer


1 Answers

A very simple example:

class View {
    function render($file, $variables = array()) {
        extract($variables);

        ob_start();
        include $file;
        $renderedView = ob_get_clean();

        return $renderedView;
    }
}

$view = new View();
echo $view->render('viewfile.php', array('foo' => 'bar'));

Inside viewfile.php you'll be able to use the variable $foo. Any code in the view file will have access to $this (the View instance) and any variables in scope inside the render function. extract extracts the array's contents into local variables.

like image 103
deceze Avatar answered Nov 14 '22 08:11

deceze