简体   繁体   中英

MVC Patern, Model in the View

I work with PHP and understand how MVC works. There is one thing I am not sure about 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? Is there any disadvantage of doing that?

Its against the concept of 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. 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.

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:

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

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