Zend_Framework- Where to Place $_GET and $_POST (HTTP Request) handling? - php

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.

Related

Isn't Controller and Model is the same in php MVC

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:

What is the right way to handle $_POST data in MVC?

I have the common MVC situation in my PHP system: the Controller receive a request from the View containing $_POST data. Now I have three ways to handle the data:
a) The Controller only calls the Model and the Model handle the $_POST data.
b) The Controller transforms the $_POST data into variables and pass them to Model.
c) The Controller transforms $_POST data into a Model's domain object and only pass the object to Model.
Currently, I am following option A, but I believe it is wrong, so I am thinking of using option C.
So, according to MVC, what is the right way to handle $_POST data?
EDIT At the moment, I'm not using any MVC framework.
EDIT 2 Generally, the same Controller handles request from a browser, a web service, an offline application, etc, or each one has it own Controller?
The best option is to use #2 approach, with some alterations.
I would write it as something like this:
public function postLogin( $request )
{
$service = $this->serviceFactory->build('Recognition');
$service->authenticate( $request->getParam('username'),
$request->getParam('password') );
}
// Yes, that's the whole method
There is no need to actually create variables, if you have used something like a Request instance to abstract the user's input.
Also, you might want to replace theRequest::getParam()method with something likeRequest::getPost()- although I have come to the conclusion that, in a correctly structured application, theGETandPOSTparameters should not share same name.
The serviceFactory which you see in the code snippet would be an object that you inject in both controller and view instance. It would let you share same service instances between controllers and views.
It is responsible for creation of services (which would contain the application logic, while leaving the domain business logic in the domain objects), which helps you isolate the interaction between domain entities and storage abstractions from the presentation layer.
About the other options:
The Controller only calls the Model and the Model handle the $_POST data.
In the MVC and MVC-inspired design patterns the model should be aware of neither the user interface nor of the presentation layer as whole. The $_POST variable in PHP is a superglobal.
If you use it with model layer, your code becomes bound to the web interface and even the specific request method.
The Controller transforms $_POST data into a Model's object and only pass the object to Model
Not entirely sure what you meant with this. Seems you were talking about instantiation of an abstraction, which would contain the user's request. But in this case controller becomes responsible for instantiation/creation of said structure, which would violate SRP.
Closing notes:
One thing you must understand is that, in context of web based MVC applications, the User of your application is the browser. Not you. Browser sends the request, which is handled by routing mechanism and disseminated by controller. And view produces the response to your browser.
And the other thing is: Model is neither a class nor an object. Model is a layer.
Update
Generally, the same Controller handles request from a browser, a web service, an offline application, etc, or each one has it own Controller?
You should be able to have single controller, that deals with all the forms of application. But that is only on the condition, you are actually using same application for all 3 use-cases.
To do so there are two conditions:
you need to abstract the Request instance, that controller receives
the view should be instantiated outside the controller
This way you can have one application to fulfill all the requirements. Only thing, that each variant has different, is the bootstrap stage, where you create the Request instance and select the proper view.
In the situation, that you described, the changing part would actually be the view, since a REST or SOAP service would be expected to produce a different response than an ordinary web application.
Once upon a time was the three tiered application architecture.
It all depends on your MVC framework. Normally, the Controller does the link between the user and the model layer, which manipulate domain objects.
In the early days of MVC in PHP, the model layer was actually just the domain objects, called models for that purpose.
Some prefered having so called thin models, which only provide an OO representation of the data, (which simplifies persistence). In that case, the controller would regroup the so called actions, containing the bulk of the processing associated with an HTTP request (fat controller).
Others embedded most of said processing in the object model with dedicated methods (fat model).
However, at some point, you have to analyse the content of the query to sanitize and validate it, and this depends on how your view will format the request. Sanitization might be a controller task (this request should only contain these values), while validation is definitely a model task (values should be of these types).
An interesting question is: how do you deal with actions impacting several domain objects? Where do you put the logic for that?
Nowadays, the model layer is composed of services segregating the domain objects from the evil grasp of the controllers, to limit the dependencies between the layers to their respective interfaces only. This is where most of the request processing is done.
Symfony2, for instance, provides a sensible answer to this question: each step of the processing of a request is implemented in a dedicated piece of code, which could be described as the following:
the request is first turned into an object
that object is routed using a routing object
it is handled to a controller
the controller pass the request to the service concerned by the action, which build the response object
The service job is then broken in several steps:
validation (using a dedicated object which rely on rules described in a separate file),
construction/updating of domain objects (using serialization to/from db if necessary),
selection of a template for the response,
population of said template with the relevant data from the domains.
CakePHP is another popular framework which follows similar concepts: simple controllers, and services encapsulating domain objects.
See this question for a better insight on the general concepts.
See this other question for other answers.
Thanks to tereško for his invaluable input on the matter.
i am using Zend and following
the 2nd option .
Example a Registration form
step- 1 the forms sends me the post value to the specified controller
step -2 i will validate the form values for example ( mail and url and empty post values ) through server side validation .
step -3 send the checked post data either in variable or has whole to the model .
step 4- controller calls the model .
step -5 the models inserts the post values and creates a new user .
I think your second option is better regardless of framework or approah you use .
note - same controller can handle everthing depends on your application logic .
but i prefer to keep different controller for differnt user request and user types
it helps in keeping code readable managebale .
Look at some MVC frameworks.
For example, in Yii you can write such code inside action:
$model = new Model();
if(isset($_POST['Model'])) {
$model->attributes = $_POST['Model'];
}
Note, that all attributes of your model must be passed through validation rules. In Yii validation applies during (actually, before) $model->save()
See:
http://www.yiiframework.com/doc/guide/1.1/en/form.model#securing-attribute-assignments
http://www.yiiframework.com/doc/guide/1.1/en/basics.mvc
'C' is best option. You should not let raw $POST data go in model as model is supposed to be generic handling store and load operations mainly.
Example : same model can be used web interface and Web services. On Web $_POST is valid but for web services its not. So model doesnt care how data is received but only how to store and load it.
Yii is definitely a clean implementation of MVC.

Implementing OOP PHP with AJAX, MVC?

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/

Why do so many MVC web frameworks favor grouping multiple controller actions in a single class?

My experience is mostly limited to PHP, yet as far as I know both Rails and ASP.NET MVC have taken the same path.
The point is that nearly every web framework I've ever come across implements controller actions as methods, e.g. create, edit, show, etc. These methods reside in a single class like PostsController, but they hardly ever share state or dependencies, because only one of them gets called during the whole request.
That's why to me this approach seems quite unreasonable, as the class only acts as some kind of namespace. Seeing examples with large chunks of barely related controller action code composing even larger controller classes doesn't help either. Yet a lot of frameworks do exactly that, and only a few use a class for each action.
So the question is, why is it so? Perhaps it's subjective, but I believe that I may have missed an important advantage of this approach.
I would argue that the MVC design pattern in general dictates this approach to building controllers. The main purpose of the controller is to provide the appropriate "wiring" between the associated view and the models it needs to interact with, along with any business logic needed to handle the input from the view. Controllers should just be a thin layer between these other components.
For example, Wikipedia describes the controller as follows:
The controller receives input and
initiates a response by making calls
on model objects. A controller accepts
input from the user and instructs the
model and viewport to perform actions
based on that input.
I do agree that controllers in other, non-web environments do maintain state, but the reason for the lack of state in PHP, for example, is simply that HTTP is a stateless protocol. Using MVC in this environment is inherently going to result in controllers that don't maintain state.
Why do so many MVC web frameworks favor grouping multiple controller actions in a single class?
That is essential to object oriented programming resulting in a properly layered software architecture where the controller objects encapsulate all responsibilities about domain objects (model). If there is a PostModel, then there should be a PostController responsible for calling the right business methods on the domain api to satisfy the user request and to push the results into the view. Having a controller class for every single possible request leads to a procedural structured architecture in my opinion.
On the other hand, if you have too many resonsibilities in your controller class, you should split these responsibilities into multiple controllers. It depends on your application at hand, there is no one-fits-all solution. Every controller should be responsible for a cohesive group of actions on the domain layer.

General on mvc... should controller pass data to view or view should grab it directly from model?

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.

Categories