如何正确地将数据从控制器传递到视图? [英] How to correctly pass data from controller to view?
问题描述
我当前的实现方式:
class SomeController extends AppController
{
function someaction()
{
$d['text'] = "ahoy!";
$this->render("someactionView", $d);
}
}
在AppController
中:
function render($file, $data = "")
{
require "views/" . $file . ".php";
}
$data
将在视图文件中可用.这是正确的实现吗?此实现有任何谬论吗?
And the $data
will be available in the views file. Is this a correct implementation? Are there any fallacies with this implementation?
推荐答案
$data
将在视图文件中可用.这是正确的吗 执行?此实现有任何谬论吗?
And the
$data
will be available in the views file. Is this a correct implementation? Are there any fallacies with this implementation?
基本上,您可以像大多数框架一样实现它.有两个问题:
Basically you do implement it like the most frameworks do. There's a couple of problems with that:
- 控制器获取输入并发送输出(这违反了单一职责原则)
- 视图与HTML紧密耦合.因此,您不能将同一视图用于其他内容,例如XML,JSON.
- 如果在
render()
方法中执行require "views/" . $file . ".php";
,则再次将其紧密耦合.如果您更改视图的位置怎么办?然后,您将不得不稍微重写您的方法.这种方法只会破坏重用能力.
- A controller takes an input and sends an output (which breaks the Single-Responsibility Principle)
- A view is tightly coupled to HTML. Because of this, you cannot re-use the same view for another stuff, like XML, JSON.
- If you do
require "views/" . $file . ".php";
inrender()
method - you again tighly couple it. What if you change the location of views? Then you would have to slightly rewrite your method. This approach merely kills reuse-ability.
要刷新您的基本知识,请执行以下操作:
To refresh your basic knowledge:
仅用于单一目的.它会更改模型状态-也就是说,它应该接受来自$_POST
,$_GET
,$_FILES
,$_COOKIE
的输入.在控制器中,仅应完成变量分配,并且仅此.
Serves only singular purpose. It changes model state - that is, it should take an input that comes from $_POST
, $_GET
, $_FILES
, $_COOKIE
. In controller only variable assignment should be done and nothing more.
class Controller
{
public function indexAction()
{
$this->view->setVar('age', $this->request->getPostParam('age'));
$this->view->setVar('user', $this->request->getPostParam('user'));
//...
}
}
查看
视图可直接访问模型.为了使视图更可重用和可维护,您最好将必需的内容作为函数参数(或通过设置器)传递
View
A view has a direct access to a model. In order to make make views more re-usable and maintainable you'd better pass required things as function parameters (or via setters)
class View
{
public function render($templateFile, array $vars = array())
{
ob_start();
extract($vars);
require($templateFile);
return ob_get_clean();
}
}
应如何初始化视图以及应如何将变量传递给视图?
首先-一个视图应该在MVC-triad外部实例化.由于控制器写入视图或模型,因此您将通过控制器传递变量以进行查看.
How the view should be initialized and how the variables should be passed to it?
First of all - a view should be instantiated outside MVC-triad. Since a controller writes either to view or model - you'd pass variables to view via controller.
$model = new Model();
$view = new View($model);
$controller = new Controller($view);
// This will assign variables to view
$controller->indexAction();
echo $view->render();
注意:在现实世界中,模型不是类,而是抽象层.出于演示目的,我将其称为
Model
.
这篇关于如何正确地将数据从控制器传递到视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!