简体   繁体   English

MVC Patern,视图中的模型

[英]MVC Patern, Model in the View

I work with PHP and understand how MVC works. 我使用PHP,并且了解MVC的工作原理。 There is one thing I am not sure about MVC. 关于MVC我不确定一件事。 Is it a good practice to create a Model object directly in the View without passing it through the Controller because sometimes there is no need to process the Model in the Controller? 因为有时不需要在Controller中处理Model,所以直接在View中创建Model对象而不将其通过Controller是一个好习惯吗? Is there any disadvantage of doing that? 这样做有什么缺点吗?

Its against the concept of MVC 它违反了MVC的概念

Don't try to break the Architecture 不要试图破坏体系结构

Model - The lowest level of the pattern which is responsible for maintaining data. 模型 - 模式的最低级别,负责维护数据。

View - This is responsible for displaying all or a portion of the data to the user. 视图 -这负责向用户显示全部或部分数据。

Controller - Software Code that controls the interactions between the Model and View. 控制器 -控制模型与视图之间交互的软件代码。

在此处输入图片说明

Reference Here 这里参考

您的view仅显示结果,因此new Model()必须转到控制器,然后再传递给视图。

Yes - your view shouldn't need to rely on the Model staying the same. 是的-您的视图不必依赖模型保持不变。

Say for example, you're using a model which has ->forename and ->surname attributes. 举例来说,您使用的模型具有->forename->surname属性。 In your view, you just call these directly. 在您看来,您只需直接调用它们即可。

Then you decide later that you're going to add mutators and accessors (getters and setters) to your model, so you'll be using ->getForename() and ->getSurname() because you want to do some pre-processing on them to ensure the capitalisation is correct. 然后,您稍后决定要向模型中添加变量和访问器(getter和setter),因此将使用->getForename()->getSurname()因为您要对它们以确保大写正确。

Now you need to go through all your controllers and views, because the usage needs to change. 现在,您需要遍历所有控制器视图,因为用法需要更改。

If you'd instead just done all the model processing in your controller and then passed a standardised set of data to the view, you'd only need to update your controllers. 相反,如果您只需要在控制器中完成所有模型处理,然后将一组标准化的数据传递给视图,则只需更新控制器即可。

A View shouldn't expect anything of the Model, it should just require that it gets specific data from a Controller. 视图不应该期望模型的任何内容,它只需要从控制器获取特定数据即可。

You could do something like this in your Controller: 您可以在Controller中执行以下操作:

$view = new View('my.file', [
    'user' => [
        'forename' => $user->forename,
        'surname' => $user->surname,
    ],
] );

this still gives you a $user['forename'] to use in your View, but now the format of that data is coming from the Controller, not the Model. 这仍然会为您提供$user['forename']以便在您的View中使用,但是现在该数据的格式来自Controller,而不是Model。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM