I am learning PHP programming and came across MVC (Model View and Controller). Can anyone explain more about Model and Controller?
In the following stack overflow question What is the best definition of MVC?, there was an answer that Model is responsible for databases. But isn't it controller which process and use database?
No, they're not the same. The Model contains everything your app can "do".
Classes which describe your data structures? Part of the Model.
Function/method/service for creating new users? Part of the Model.
Sending email notification? Part of the Model.
Complex database queries? Part of the Model.
Everything else? Part of the Model.
What the Controller is is an "interface between your Model and the outside world." The Controller takes input from outside world, like an HTTP request, or a command line input, or an event on an event bus, and decides based on that input what action should be triggered in the Model and perhaps with what kind of View to respond. You may have different Controllers for different scenarios (web server, command line interface, cron job) which adapt those different scenarios to actions in the underlying Model.
for MVC in PHP, i've found Codeigniter to be very useful! Altough it differs a little from MVC in other Languages...
here from theyr definition:
The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.
The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.
https://codeigniter.com/user_guide/overview/mvc.html
No, controller and model is not the same in MVC architecture. The model is being used to keep track of all the business data. The controller tells it what to do, and the model knows how to do it.
Controllers orchestrate the application. Controllers receive events from the
outside world (normally, user input), interact with the model, and display an
appropriate view to the user.
The model is responsible for maintaining the state of the application. A model is more than data; it enforces all the business rules that apply to
that data.
To learn how the concepts fit together, see the
following figure:
Related
What do I want to do?
I am trying to create a little application in PHP to manage user requests and registrations. I am not using any MVC framework, but I want to make it following the MVC because I want to scale it and reuse the code of some components.
My Question:
If the Controller does not manage the View, how can it access the mail's final presentation (content+format) before sending it?
In which guidelines I want to base it?
I have read some articles about MVC in web applications, and I have intention to meet the following specifications:
The Model:
In its simplest form the model stores data which is to be accessed by the view and written to by the controller. The model is the most complex of all the parts of the system and will contain all the logic which is specific to the application and where domain entities that relate to real world concepts (such as "a user" or "an order") are stored. It is the part of the application which takes data (from any source) and processes it. The model also handles all data access and storage. It has no knowledge of any controllers or views which may use it.
The View:
The view contains all the display logic. In PHP it will be the part of the application which generates the HTML. It has direct access to the Model and can query the model to get its data. The View can create callbacks to its controller (for example a clicking a button in the view would trigger an action in the controller). In MVC the view queries the model to request its own data.
The Controller:
The controller takes user input and updates the model where required. Where there is no user interaction (e.g. where a static data set is displayed and will be the same every time), no controller should be necessary. It is important to note that the controller is not a mediator or gateway between the view and the model. The view gets its own data from its model. The controller accesses the model but does not contain any display logic itself. All the controller does is respond to user input.
It's important to note that the controller is not in charge of instantiating the model or the view. Each controller is linked to a single instance of a view and a single instance of a model.
The above specification could be summarized with the following diagram
Trying to do it with Mailing Case
So I assume that the Controller is the one that is going to send the email(s) and the View is the one that is going to prepare the email(s) presentation.
The more detailed version of the previous diagram, adapted to the mailing case (please, notice the discontinuous arrow with an interrogation, as it is where my question lies):
Is there anyway to keep the following general program flow?:
//initiate the triad
$model = new Model();
$controller = new Controller($model);
$view = new View($model);
$controller->{$UserRequest};
echo $view->output();
I do not find any solution to this. Is there any way to proceed that I cannot find?
Thank you guys for your help...
Mail is generally considered as a part of "helper class".
Indeed, mail should be sent through the controller class, but defined in helpers for more clarity.
You can use phpMailer for example (really easy to use in MVC).
I have the following data flow for a simple login form.
User access controller PHP file. Controller includes model.php and view.php
User submits form, controller sends POST data to model methods, and gets a result back.
User is logged in, and forwarded to a different view (login success message) by the controller.
Currently my views are static HTML (no PHP), so here is my question. What is the correct way to then pass the user a welcome message, e.g "Hello, Craig!"?
Is the view allowed PHP snippets, e.g
<?php echo $username; ?>
since the model is loaded before it in the controller file?
Thanks!
Edit: Is it better practice then to allow the view to access specific class methods e.g
<?php $user->getUsername(); ?>
as opposed to just variables?
Based on other answers, I have found a very useful article, which you may also be interested in.
http://www.nathandavison.com/posts/view/7/custom-php-mvc-tutorial-part-5-views
Here are few things you must consider:
You cannot do classical MVC in PHP. Instead we have MVC-inspired patterns
There exists 1:1 relation between view and controller instances, when implemented for web
Model in MVC is not a class. It is a layer, that contains a lot of different classes
View is not a dumb template, but an instance of class, which deals with presentation logic
View in Web-based MVC
As stated above, views in MVC and MVC-inspired patterns are responsible for presentation logic. That encompass things like showing error messages and pagination. To do this, each view can handle several templates.
View receives information from the model layer, and acts accordingly. The way how the information from model layer ends up in views is one of most significant differences in MVC-ish patterns:
classical MVC pattern
Structures from model layer send the information to view, when state of model has been altered. This is done via observer pattern.
Model2 MVC and HMVC patterns
View has direct access to the model layer and is able to request information from it. This is the closest to the original pattern.
MVVM and MVP patterns
View receives information through controller, which has in turn requested it from model layer. The further difference in patterns stems from what the do with data before passing it to view.
What you seem to have now is actually just a template. Similar to one, that is described in this article. You end up with a structure, that has no place to contain the presentation logic. In long-run this will cause the presentation logic to be pushed into controller.
So what about that "welcome" message ?
To show the welcome message, your view should request from model layer the name of current user. If the model layer returns some sort of error state, view pick the error message template and inserts into the layout.
In case if name of the user was retrieved from model layer without problems, view pick the template which would contain the greeting, sets the value in the template and renders it.
In what order parts should be loaded ?
The idea, that controller should initialize model and view, comes from very primitive interpretation of MVC for web. Pattern know as page controller, which tried to graft MVC directly on static web pages.
In my opinion, this should be the order:
Model
You initialize the structure, through which you will deal with model layer. It most likely would be some sort of service factory, which would let you build things like Authentication service for logins and Library service for handling documents. Things like that. I wrote a bit long'ish comment on model layer's structure earlier. You might find it useful.
View
You create a view instance based on information, that you collected from routing mechanism. If you are implementing Model2 or HMVC, then your view will require an instance of Service Factory in the constructor.
If you are implementing MVVM or MVP, then view's constructor has no special requirements.
Controller
This is the last structure, which you create, because controller is responsible for sending commands to both view and model layer, which then change then change the state of both. Therefore controller should expect to receive both view and service factory in the constructor.
After basic elements of MVC have been initialized, you call a method on the controller, and render current view.
Just keep in mind that this is very simplified description.
You can really put anything in a view that you'd like, but to better adhere to the MVC way of doing things you should restrict PHP in the view to simple echos or prints (possibly really small loops as well, although even those can be pre-calculated in the controller/model). Since that is the only way to get dynamic content, it would be a little silly to say that they are not allowed.
The idea of the view is to let it have a more HTML look-and-feel, so that front-end developers or people who don't know PHP can easily be able to work with the file without getting confused.
Update
To learn more about MVC in general, you can see any of these (there's a ton of tutorials out there):
http://blog.iandavis.com/2008/12/09/what-are-the-benefits-of-mvc/
http://php-html.net/tutorials/model-view-controller-in-php/
http://www.tonymarston.net/php-mysql/model-view-controller.html
To see concrete examples of PHP using MVC, I suggest downloading some of the more prevelant frameworks (such as CodeIgniter, Symfony or Drupal) and just looking through the code. Try to figure out how it works and then recreate the functionality for a simple article-based system.
When should a new model or controller be made? Should there only be controllers that go with a corresponding view 1 to 1 and like so with controllers and models? Or is it good practice to have controllers for functionality not tied up with any particular view? Take for example voting, should all voting code go in a voting controller or be spread among controllers that have views using voting. Seems likely a voting controller would be best.
First of all , you cannot actually implement classical MVC in php. The best you can do is Model2 MVC.
Model - responsible for all the business logic. Has no clue about where the data is stored or actually comes from. The storage and retrieval is responsibility of DataMappers or DAOs. Model itself should never contain SQL. Ever.
Controller - binds model(s) to the view and changes the state of both. It does not retrieve information from models for sending it to view.
View - responsible for all presentational logic. Retrieves information from models and binds it to appropriate templates. View itself is not a template.
You can wither have 1:1 relationship between views an controller or many:many. it depends on how you implement the view itself.
For example, your view can require a separate object which handles the rendering. And providing different type of objects ( this is where polymorphism matters ), you can make your view to render either xml, html or json.
Or you can do the same by changing the templates. A ListView class can render a list of articles as well as list of users, if the basic presentation logic does not change and you provide just a different template for each.
In the case of voting , it seems ok to have a single controller for all voting related operations, and you can have a single view with switching the templates for your output.
Some of this sort of thing is down to preferences and opinion; there's no single correct way. Some approaches might be more flexible, but maybe at the expense of being more complex.
With regard to your example of "voting", that may depend upon how voting is going to be used in your site. Will votes appear on different types of pages? If so, some sort of component is a good approach; the voting component view can then be used to display its data within different pages, with a Voting component controller accepting the results of votes and then maybe redirecting somewhere else (or accepting votes by an Ajax request).
Very often you'll find that a models (and controllers) map more or less 1:1 to tables in a database. So if I have a table users, I might have a corresponding User model, and UserController controller.
Remember what a controller is intended to do: respond to a request, working out which models need to be loaded, then asking them to store, manipulate and return data which is then transferred to the view for displaying. It's fine to have controllers that don't map directly to models. You might have a controller called DebugController that responds to requests to http://examples.com/debug/, and doesn't map directly to a Debug model and table, but gathers information about the system and various models (of course, there is the argument that all that stuff should be wrapped up into a Debug model, which in turn loads other models and assembles the data that the controller requests).
As for views, you will normally have more than one view for a given controller; often one view per action. So UserController::indexAction() has views/user/index.php, UserController::editAction() has views/user/edit.php etc.
The approach might be flexible, that is true.
Models - Describe the tier that is communicating directly with database, all the SQL queries.
You can have model for each table in DB that will handle all actions connected to that table (select, insert, update, delete).
You can have model for each "logical entity", modul in your application that will handle the actions for this entity. Like in your example "Voting", where you can define the logic of this modul.
(Check if the user has allready voted, getVoteCount...)
Controler - Handle the request by executing functions in the model (they should not comunicate directly in DB) and passing the processed data to appropriate View. If you need to present the same data differently on different page, the controler should decide on which view to send the data.
View - You need view for each page, form, module in you application. It is on personal experiance how you are going to organize the views.
I’m trying to learn and fully understand mvc pattern and learn php at the same time. I decided to built basic mvc framework that I could use on various projects later on. Having read lots of posts in here regarding mvc and coupling between models/views/controllers I’m a bit lost.. At the moment my understanding is that in web application controllers deal with coming request from browser and, if necessary, calls methods on model classes telling models to change its state. Then controller instantiate appropriate view class that will be responsible for displaying interface.
Here's the bit I don’t understand...
Now should controller pass appropriate model object to view and view should pull out all the data from model when needed?
Or controller should grab data from model and pass it to view, possibly wrapping it all into single wrapper object that view will access and grab data from there?
Or view should simply instantiate appropriate model when needed and pull out data directly from model object?
From what I read here
http://www.phpwact.org/pattern/model_view_controller
I’d lean towards the 3rd option where controller doesn’t pass anything to view and view instantiates model it needs. This is because:
view and controller should have same access to model
controller shouldn’t act simply as mediator in between view and model.
Is there really one correct way to do it or it rather depends on project? Also what approach would you recommend to someone who has decent understanding of OOP but is relatively new to php and not too clear on mvc architecture. Or maybe I should go with whatever seems right to me and learn from my mistakes (would like to avoid this one though ;)?
Now, please let me know if my question is not clear will try to better explain then.. Also I read lots of posts on stackoverflow and numerous articles on different sites, but still would appreciate help so thanks in advance for all answers.
Personally, I've always been a proponent of #2. The view shouldn't care about the model. The view shouldn't have any processing at all for that matter. It should do what it's supposed to do, format data.
The basic flow of control should be thus: The controller recieves a request from a browser. It processes the request, decides what data is needed, and retrieves it from the model/s. It then passes the data into the view which format the data and displays it.
As an extension, user input is processed inside the controller, and saved into a model if needed, then feedback is fed into a view, etc. The key point to take away is that processing happens inside the controller.
Personally, I've always been a proponent of #3. The view shouldn't care about the controller. The view shouldn't have any dependency on the controller for that matter. It should do what it's supposed to do, show a view of the model.
The basic flow of control should be thus: The controller receives a request from a browser. It makes any updates to the model, that is relevant, and then selects a view. The control is then passed to the view, which gets data from the model and renders it.
As an extension, user input can be consider part of the model, and both the controller and the view may read from it. The key point to take away is that Controller and View should have no dependency on each other. That's why the pattern is called MVC.
Now, personally, I find MVC a bit too tedious, and so I usually conflate Controller and View more than this. But then that isn't really MVC.
Web MVC and Desktop MVC are two very different beasts.
In Web MVC, a link in a View calls a method on a Controller, which updates a Model, and then redirects to an appropiate View, which opens up a Model and shows what it needs.
In a Desktop MVC, option 3 is wrong because both the view and the model should use the same reference. In Web, there's no choice.
Option number 2 is not MVC. It's MVP, wherein the Presenter is a mediator.
A Controller has Write-Access to a Model; a View has only Read access.
This is a very interesting question.
From my experience most implementations in php assign a model variable to the view:
$this->view->my_property = $modelObj->property
This is common practice.
The common reasoning for this is that if you send the object then you can call methods that modify the object from the view.
//in the controller file
$this->view->myObject = $modelObj;
//in the view file, you could call an object modifying method
$this->myObject->delete();
And modifying the model from the view is considered bad practice. Some people thing that they don't want their designers being able to call model modifying methods from the view.
That being said. I don't agree with the common practice and tend to assign the whole object to the view and display it from there. And just discipline my self to not make operations there.
And a third option is to assign the whole object to the view. but some how in the objects disable methods when they are called from the view.
I think this is just a generic argue about what is better "push" or "pull" model. There is no "absolutely" best solution.
I had a very similar question earlier. I find helpful to think of it as follows:
MVC
Model -- Data store, alerts Views of changes
View -- Displays model, provides hooks for user interaction
Controller -- Handles user input
You would use MVC more often in non-web apps, where lots of classes are interacting with eachother simultaneous.
In a web application MVC means MVT (Model-View-Template)
Model -- Strictly a data store, typically an ORM solution
View -- Handles web requests, provides for user input/output
Template -- Actually displays content (HTML, Javascript, etc.)
So in a web application the presentation is handled in the Template, the logic behind the application is handled in the View (or classes called by the view), and the model is responsible for holding data.
The reason why so many developers today can't get the knock of MVC is because the abbreviation of MVC was incorrectly stated from day one when it arrived into software development, but the concept is correct back then and also today. Since I am from the old school, let me explain it for you; when you are creating an object you first create a Model so the customer can View it, once it is approved you will have full Control on how the object is going to be made. That's how it is to this day in product manufacturing.
In today’s web application development such term should be VCM. Why! You View what's on the web browser, and then you click a button for action, that is known as the Controller. The controller alerts the Model, which is the instruction or logic to produce a result (that is your script). The result is then sent back to the user for viewing. In software engineering, you can refer to it as CMV; because the user won't able to view anything until the apps is compiled and installed. So we will need a Controlling device (PC); the OS as the Model and a monitor to View the results. If you can understand those concepts, MVC should start to look much more appetizing. I hope this concept will help someone to understand MVC.
I tend toward having the controller act as an intermediary between the model and the view, but generally this is literally a single line of code that connects the three together. If your model, view, and controller are properly decoupled it should make very little difference which you use.
I recently read this post which led to a series of other posts that all seem to suggest the same idea: Models do everything, the View should be able to communicate directly with the model and vice versa all while the Controller stays out of the way. However, all of the examples shown are fairly simplistic and none really show an example of how anyone has tried to implement full handling of of a request / response cycle, which got me to wondering "should the model be responsible for handling the request (ie $_GET, $_POST, etc) itself?" and "should the controller only operate as a pass-through to instantiate the necessary model(s) and pass the model(s) to the view?". (In fact I found one example taken the extreme of embedding a Zend_Form object in the model)
From my reading of what Fowler says about MVC and just controller's in general it seems at first glance that the thinner the controller layer the better. But then I took the time to back through and study what he says about both MVC and Front Controller (which just muddies the waters because both patterns define controllers) and now my instincts suggest that Zend_Framework in implementing both of these patterns, has actually created a composite object that performs the functions of a Controller in MVC and those of a Command object in Front Controller (or some such).
So I'm wondering what the general opinions would be of others who have implemented similar patterns in their apps - do you handle the request entirely within the controller layer or do you make the model aware of the request and handle parameters directly within the model?
My first thought is to avoid handling any sort of request in the model. That is the job of the controller. Here is why: suppose you have a model that does handle your requests (GET or POST). That structure will likely work well initially. Now, suppose you want to add some sort of AJAX functionality or put up a service interface to your system. Now that you accept more than simple GET/POST, i.e. JSON or XML, your model will have to distinguish between each request type and know how to parse them. I believe that destroys a lot of simplicity and clarity of the model code. I agree that the controller layer should be thin, but it should also have a role and an expertise. For me a controllers expertise is to:
Handle incoming requests
Delivery data to the model
Request/accept data from the model
Pass the data's model to the view
I vacillate on how much the view should know about the model. Some people recommend the model go straight into the view, but I think that is fragile coupling. It frequently leads to logic in the view. Also, if you are working on a project where the team members working on the view are not as programming savvy as the main developers it puts a large burden on them to keep up with changes. I tend to package the data I hand to my views in a neutral structure instead of handing over the full models.
My interpretation of MVC is mostly pragmatic. The model's job is to model the domain you are working on and should not care where the data comes from. I frequently structure model code with the assumption that it could be used outside of the web application in perhaps a command line application or a desktop application. That sort of union rarely happens, but it leads to clear purpose of each layer. The controllers job is to move data between involved parties, be they client requests, the models, or the view. The controller should have very little domain logic, but that doesn't mean it doesn't have any code. Finally, the view should just look pretty. Hope that helps.
handling the user instructions/input (like HTTP requests) is the job of the controller. model is for working/manipulating/fetching the data and view is for showing the results to user. this means that connection between the view and the model is duty of a controller most of times.