简体   繁体   中英

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?

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.

    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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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