I'm new to the OOP paradigm (and AJAX/jQuery), but would like to create a basic site employing MVC architecture, in PHP, with AJAX functionality. I drew up a brief diagram of how I currently 'understand' the architecture.
Presumably when AJAX is used, that acts as the controller to interact with the model directly to retrieve whatever functionality is needed? The filenames I added are just to give you an idea of what I 'think' should be included. e.g. index.php would be a html/css template with includes to modules in the relevant places (whatever they may be) - news.php, navigation.php, etc. database.php/pager.php might house the classes and extended classes that I create for pagination, or connecting/querying the database I'm struggling to see what the controller component could be - it'd surely end up being a 'second back-end view' - calling the classes from the model to be sent to the view?
I've probably portayed my confusion well here - what should go in the view, controller and model... is AJAX functionality technically another controller? Any diagram similar to my one above would be extremely helpful.
OK so AJAX is a transport method and not a piece of application like a model or controller.
Your client will communicate through AJAX with one or more Controllers.
These Controllers use or invoke Models to handle different kind of tasks.
Then either the controller or the model responds to the request either with a message in a transport-friendly format (JSON, YAML, XML) or with a View (piece of HTML).
The controller handles requests, that means it receives the initial client-input. Depending on the situation this input has to be formatted, normalized, mutated or transformed somehow before being used in your application.
Then a controller uses or invokes a model; this means that it either deals with business logic itself (old style) and makes use of the model to access datasources or it hands the main workflow of your application completely over to the model (new style).
A model in first instance abstracts a persistent storage entity (like a database). In contemporary application design it also does the main business logic of your application.
There's one way to see this.
Ajax is the medium for sending data between MVC components like HTTP POST. In this respect it does not show up in the MVC pattern.
The actual display in JSON format can also be seen as a view if it's actually used to show data.
From this you should be able to come to your own conclusions.
You can use PHP's best MVC architecture called "YII".Get more info from here
http://www.yiiframework.com/
Related
This is a question about theory, so there is no need for code snippets.
I built a router that, as a typical router does, dispatches a controller based on the URL. The workflow is something like this:
Router dispatches controller and instantiates it
Controller renders a view
User interacts with the view
Controller updates model based on user interaction
Model returns the new state of the data to the controller
Controller updates the view based on new data
So basically, the controller is the starting point and the link between the model and view. The model and view never directly interact with each other. The controller is the workhorse and has most of the code.
Now, that is all good and I get it. The confusion comes when I read articles about MVC design patterns and realize what they describe is not what I just described above. It seems like, in the pattern you start at the view. The view talks directly to the model and the controller accepts user interaction to update the model.
So, what I'm doing may involve models, views and controllers, but its not strictly the MVC design pattern. I did read one article where they called what I first described as CAV, controller action view.
My question is, what is it that I'm describing? I don't want to keep referring to it as MVC if its not actually MVC. From what I read true MVC was birthed in the 70's. Things have changed since then. Perhaps what I'm doing is some evolved version of MVC, but not MVC in its strict form. Is there another name for it so I can stop confusing myself, and others, by calling it MVC?
I think its language (technology) dependent.
You tagged your question with the php tag, so I suppose you're developing applications using this language. In a classic PHP application, the view can't get updates from the model (in fact, this more related to the PHP language being executed only on the server).
First, the entire application is launched for each request and is terminated when all the response has been sent. So, the router is called for each request.
Then, the router execute the controller which have to handle the request (according to routing rules).
The request being for reading or writing does not modify this behavior.
If you want to allow the view to ask for data modification approval to your controller, you may need to use some client-side programming language (Javascript). So, you may use a REST API to handle communication between the model and the view.
To answer your question, I think you can't implements a pure MVC design pattern on a client-server model without using a programming language on the client.
Even I faced this confusion previously. In the original form, View did interact with the controller. They followed the observer-observable pattern. This was how MVC was conceived in SmallTalk. However, The version of MVC that you are talking about is actually a modern version of it and is used in most frameworks. It sort of has became a standard. I do not know of any other term for it. In this version, the controller is actually a bridge between view and model. However, both of the patterns achieve the desired objective of separation of concerns.
I am thinking about using Symfony to create a RESTful api. I want my app to only accept json and/or xml and just output either. I want my frontend to be completely separate in a separate directory.
Disclaimer: I know most frameworks only claim to be MVC, and that the definition/principles of MVC vary from developer to developer. Therefore, I've laid out my understanding of MVC.
How I picture MVC (taken from Martin Fowler):
Make a strong separation between presentation (view & controller) and domain (model)
Controller and view should (mostly) not communicate directly but through the model.
Have views (and controllers) observe the model to allow multiple widgets to update without needed to communicate directly - Observer Synchronization.
In Symfony, the Controller returns a Response, and there really isn't a View class. They sort of combined the two.
My questions are:
Is it possible to separate the controller into a controller and view?
Can you make the controller not return something?
Possible to not have any html/templates within the app/bundle?
As I stated earlier, I want to keep frontend completely separate, therefore, I wouldn't use twig. I would use JS, SASS, React, etc. for my frontend stuff to make ajax calls to my Symfony api.
What you are trying to do is a pretty standard architecture.
You do not need to use templates but your controllers have to return "something". If you are handling the view in the front-end, this would be just the data needed to create this view, usually in the form of json
Symfony can do this, no problem
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.
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.