简体   繁体   English

MVC接线; 查看和模型

[英]MVC Wiring; View and Model

According to this answer, it seems to be ok to call model from the view. 根据这个答案,从视图中调用模型似乎没问题。

Can I call a Model from a View? 我可以从视图中调用模型吗?

Now my question is, how would the wiring look like? 现在我的问题是,布线怎么样?

Would the controller pass a Model Factory to the view? 控制器会将模型工厂传递给视图吗? (Which I think would defeat the purpose of this question, since it would have to bypass the controller in order to do that unless I'm understanding wrong) (我认为这会破坏这个问题的目的,因为除非我理解错误,否则必须绕过控制器才能这样做)

Or 要么

Would the View have a model factory injected in View's constructor before the view gets passed to the controller? 在视图传递给控制器​​之前,View是否会在View的构造函数中注入模型工厂?

At first glance, I don't see a problem with that. 乍一看,我没有看到问题。 Let's walk through the alternatives: 让我们来看看替代方案:

  1. Passing the raw model into the view, type hinting off generic model interface 将原始模型传递到视图中,键入提示通用模型接口

    On the surface, this may seem ok. 从表面上看,这似乎没问题。 However, if your models aren't consistent in their apis (such as $model->getPerson($id) , which is fairly likely), this is effectively tightly coupling the controller model and view together. 但是,如果你的模型在api中不一致(例如$model->getPerson($id) ,这很可能),这实际上是将控制器模型和视图紧密耦合在一起。

    Since your view can't really accept any model, injecting the raw model from the controller may be a bit too liberal and open the door to inconsistencies or weird errors down the road. 由于您的视图无法真正接受任何模型,因此从控制器注入原始模型可能有点过于自由,并且在未来的道路上打开了不一致或奇怪错误的大门。

  2. Passing the raw model into the view, type hinting off the desired model class 将原始模型传递到视图中,键入提示所需的模型类

    This solves the liberalness problem from the prior solution, in that only the correct model can be passed. 这解决了先前解决方案中的自由度问题,因为只有正确的模型才能通过。 But now you've further coupled the view to that model. 但是现在你进一步将视图与该模型结合起来了。 So that's not good. 所以这不好。

  3. Instantiating the model inside the view. 在视图中实例化模型。

    This is also not an ideal solution, since now you can't mock out your model for testing and have completely coupled the view to the model. 这也不是一个理想的解决方案,因为现在您无法模拟您的模型进行测试,并将视图完全耦合到模型中。 A definite SOLID violation. 明确的SOLID违规。

So that basically leaves injecting the model's factory. 所以这基本上是注入模型的工厂。 It allows the view to determine which model it needs (and hence asks for from the factory). 它允许视图确定它需要哪个模型(因此从工厂请求)。 It allows the model to be mocked out (by swapping a different factory). 它允许模拟模型(通过交换不同的工厂)。 And it also allows for arbitrary models to be passed, by adjusting what the factory returns. 它还允许通过调整工厂返回的内容来传递任意模型。

So the dependency is now loosely coupled, and you're instead dependent upon a factory (which is a better dependency to have). 因此,依赖关系现在松散耦合,而您依赖于工厂(这是一个更好的依赖)。

That's my first thought. 这是我的第一个想法。 I'd need to think about it further to see if there's a cleaner solution, but there you have it... 我需要进一步思考,看看是否有一个更清洁的解决方案,但你有它......

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

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