Do I need to create a Model for every Controller? What is the better practise?
Let's say I 开发者_开发问答have a Model 'Retrieve.php' where I have a class named 'Retrieve' and it retrieves posts from a database. Then I have Controller in Index.php
where I load that model, retrieve posts and pass it to view.
And now, I have one more page where I have to show those posts. Let's say Sidebar.php
or something. And now again, I have to retrieve those posts. So, can I load 'Retrieve.php' once more, or I have to create one more model for Sidebar.php
which extends 'Retrieve.php'? What is better practise?
And, in general, do I need for every controller create a new model in a good PHP MVC? If yes, probably Controller and Model should be named the same? Any more advices/comments?
Thank you.
In general, the model should represent a business entity and not a process. I.e., it should be a noun and not a verb. In your case, you want a model for a post, and the methods on that model will perform "the things you do with/to a post." The controller then describes what actions occur for a page. In this case, a controller for the /post page would retrieve a post and pass it to the view for rendering.
Only create the models you need. Remember, the whole point of MVC is that the models are decoupled from the views. This means it's perfectly fine to reuse whatever you need to get the job done. If you have multiple views which need access to the same data, just reuse the same model. Just be sure to give the models descriptive names so there's no confusion as to what they're supposed to represent.
You should only have one Model class for each data structure that that model represents. So if you have 5 Controllers that each access the same Model, you should still only ever have one Model class.
No --
Model should be what your application manages -- so instead of Retrieve, your model class should probably be Post (and maybe you have other Model classes for the nouns in your domain-- Thread, Author...)
The controllers should access the model classes they need to do their jobs; one model class could be used by several controllers, and one controller could use several model classes.
精彩评论