8

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!

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've been trying different ways of implementing this view class. Where do I exactly include this view class? I've tried creating a controller property of an instance of class view and have one of the controller's method render a variable to be use in 'viewfile.php' but it doesn't seem to work. It maxed out the buffer so I had to modify it to include_once $file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.