开发者

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 f开发者_StackOverfloweatures 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜