自定义MVC,如何为控制器实现渲染函数,以便View可以访问Controller设置的变量
我正在向现有代码库添加新功能。无论如何,我认为我目前正在做的功能应该是在 MVC 中。现有的代码库不是 MVC,但我正在实现的功能,我希望它是 MVC。而且我不想将一些现有的 MVC 滚动到现有的代码中。
所以,我的问题是......我不知道为控制器类实现渲染函数。通常,在 MVC 中,您让控制器执行一些操作,使用渲染函数将其设置为变量,并且视图现在可以神奇地访问控制器设置的给定变量。
除了全局之外,我不知道如何做到这一点,这只是感觉不对,我不断告诉自己必须有更好的方法。编辑:这是全球性的,不是吗? >>_>>其他框架是如何做到的?
这是一个愚蠢的例子:
控制器:
class UserController extend BaseController
{
public function actionIndex()
{
$User = new User; // create a instance User model
$User->getListofUser();
$this->render('ListOfUser', 'model'=>$model);
}
}
视图:
<?php
//I can use $ListOfUser now...
//some for loop
echo $ListofUser[$i];
?>
提前谢谢您!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个非常简单的示例:
在
viewfile.php
中,您将能够使用变量$foo
。视图文件中的任何代码都可以访问$this
(View 实例)以及render
函数内范围内的任何变量。extract
将数组的内容提取到局部变量中。A very simple example:
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 therender
function.extract
extracts the array's contents into local variables.