What is MVC, in relation to the Zend framework? - php

I'm learning the Zend Framework and it uses a MVC model.
I still have not got my head around what MVC Model, View, Controller is.
What are the three different areas for and what would the program flow look like?

M - Models - are often the biggest source of confusion. These are the parts of your application that do all the 'heavy lifting' - they handle database access, perform the complex application-specific logic and are responsible for most of what your application 'does'. Unlike Views and Controllers, the Zend Framework doesn't have a base class for Models - this is because there's no real consistency in what they do. Some frameworks (like Ruby on Rails) try to present some sort of database-wrapper as a base for Model, but there are many cases (3rd party feed/API, static files, non-persistent calculations, concepts that span multiple tables...) for which this is, at best, a misleading practice. The Model is the part of the application where you're still forced to program and the framework can't really save you from it.
V - Views - are the simplest components here. They should be simple PHP/HTML templates. They're given view objects, arrays, strings, etc. which they then put into a page. There shouldn't be much (if any) complex logic here - loop over these, display this (if defined), zebra stripe this table and whatnot. There's some magic happening with View Helpers (such as the helper that magically renders a Zend_Form), but that's not essential to understanding the overall system.
C - Controllers - In the broadest sense, the controller is responsible for taking user requests, sending them off to Model objects and preparing Models to be handed to the Views. It's the glue that holds everything together. If you're using Zend MVC, you're concerned with 2 controllers - Zend_Controller_Front and Zend_Controller_Action.
Zend_Controller_Front (which you get 'for free' if you use Zend_Layout::startMVC()) is a single point of entry for your application - it handles the raw user requests and translates URLs into an Action to call. There are various places to 'plug-in' to this to handle things like authentication and access restrictions, but, at the core it's just the 'traffic cop' at the front gate directing incoming requests.
Zend_Controller_Action is the base class for actions - essentially an Action represents something your application does (log in, list blog entries, launch an ICBM, order a pizza...), but is not directly responsible for actually doing it. The Action Controllers are pretty boring - they pull values out of forms and URLs, call a few methods on Model classes to actually perform the action and push the results out into the view. As has been said before, they're the 'glue' that holds Models and Views together.
A rough test to see if you're splitting things along the right lines is to envision a major change to your site. A visual redesign would almost entirely be handled in the Views. Moving all your URLs would change your Controllers. Converting from a web app to a GUI app would replace the views and controllers, but your model would still be mostly unchanged. If you rewrite your models, you have a whole new application.

There are several other questions on Stackoverflow that give an explanation of the MVC concept:
What are MVP and MVC and what is the difference?
What is MVC (Model View Controller)?
A very good explanation of the concept can be found on Wikipedia:
Model-view-controller (MVC) is an
architectural pattern used in software
engineering. Successful use of the
pattern isolates business logic from
user interface considerations,
resulting in an application where it
is easier to modify either the visual
appearance of the application or the
underlying business rules without
affecting the other. In MVC, the model
represents the information (the data)
of the application; the view
corresponds to elements of the user
interface such as text, checkbox
items, and so forth; and the
controller manages the communication
of data and the business rules used to
manipulate the data to and from the
model.
In relation to Zend Framework:
models are generally presented by extensions of the Zend_Db_Table class
views are presented as *.phtml files in your defined scripts folder, which are handled by the Zend_View class.
controllers are defined by extensions of the Zend_Controller_Action class.

The Zend Framework has its own very nice Quick Start/Tutorial which especially introduces MVC.
Quote from there:
So what exactly is this MVC pattern
everyone keeps talking about, and why
should you care? MVC is much more than
just a three-letter acronym (TLA) that
you can whip out anytime you want to
sound smart; it has become something
of a standard in the design of modern
web applications. And for good reason.
Most web application code falls under
one of the following three categories:
presentation, business logic, and data
access. The MVC pattern models this
separation of concerns well. The end
result is that your presentation code
can be consolidated in one part of
your application with your business
logic in another and your data access
code in yet another. Many developers
have found this well-defined
separation indispensable for keeping
their code organized, especially when
more than one developer is working on
the same application.

In as few words as possible:
model is the db
view is what you see (the page)
controller is the glue (logic)
Your models know how to access tables containing your data; your views know how to display content; and your controllers glue it together (what view do I show? what model should I use?).

Related

Models in Symfony2, and other MVC frameworks?

I'm trying to understand how Models work in proper MVC.
As far as I know, Models in MVC is where the application logic happens, Models are meat, or back bone of MVC. Views are just presentation, and Controllers are "glue" that asks Models to do some actions, return some data, and pass that information to the View that is presented to the user.
Now, I'm exploring all kinds of different MVC frameworks and would like to understand how to use models in MVC. Symfony 2 is interesting framework as far as Models goes, since there are no Models :)
I have problems grasping some of the features of Symfony2, and where does Models fit in Symfony2 MVC.
By definition, Models are where domain logic, and database actions goes.
So my questions are:
In Symfony2 we have Entities, and Services, are those two Models in Symfony?
What is the difference in Symfony2 Services, and Web Services?
So my questions are where is the Model in Symfony2? Since Model is a layer, composed of Domain Objects, and Data Mappers, then I can assume that Entities are Domain Objects, and Doctrine is Data Mapper, is that correct?
And where do Symfony2 services fit in?
Symfony2 does not have the traditional "Model" part of MVC like other frameworks do. Even Entities/Documents from ORM/ODM Doctrine are not part of the framework itself nor does Symfony2 depend on it.
As Fabien (creator of Symfony framework) wrote on his blog,
"It's up to you to create your model by hand or use any other tool,
like an ORM" ... "I don't like MVC because that's not how the web works.
Symfony2 is an HTTP framework; it is a Request/Response framework."
It was hard for me to understand just reading, but I understood what he meant when I actually started programming in Symfony2.
A service in Symfony2 on the otherhand is just an object that performs a global task. Router, doctrine, logger, mailer are some of the many services that come preloaded with Symfony2. You can access services from any part of your code.
Symfony2 services are completely different from web services. Symfony2 services are meant to be used within your system while web services are meant to be used from machine to machine via REST api for example. Although, I guess you could create RESTful api as part of your service.
"I don't like MVC because that's not how the web works. Symfony2 is an HTTP framework; it is a Request/Response framework."
I disagree with this statement completely. MVC is definitely suited to the web if you look at it the right way.
1) The HTTP request is received by the Controller.
2) The Controller instantiates the Model (or Models) and activates the relevant method(s) on the Model(s) which each return a result which will usually be an array of data.
3) When the Model(s) have finished the Controller instantiates the View, inserts the data from the Model(s) then activates the method which transforms the data into HTML.
4) The Controller takes the result from the View and sends it back to the client as the HTTP response.
Just because MVC was invented for desktop applications years before the web existed and is therefore irrelevant for the web is a mistake made by people who cannot see the wood for the trees, who cannot see the big picture without fixating on irrelevant details. Each component in MVC has a distinct set of responsibilities, and provided that you create three components each of which fulfils one of these responsibilities - where the physical implementation is irrelevant - then you have MVC whether you like it or not.
I don't know Symfony but I already use other MVC frameworks (grails, codeigniter).
Models (Entities) represents the data and it is possible to define directly in the models some limits used later for the validation. For example, you can define for each attribute if it is required, its length, its pattern, ...
Services is maybe more symfony dependent. Comparing with Grails, Services are the components where you put your business code. In Java EE, it is the Beans. Note that a service can become a web service but it is not mandatory. A Service can also be called by the Controller in order to do some calculation before rendering the view.
I hope that my answer can help.

MVC:: Which goes where?

I was a flat php programmer for past 2 years. Now I want to move to MVC architecture and so I am using codeigniter which looks very simple to start with. I want to know some of the best practices out there as I go developing in codeigniter.
I have a controller called building, a model called building_data and a view called building_view. Now i want to display list of building by checking lot of conditions. I am doing the following in flat PHP
Get the list of buildings from database
Split the result based on certain criteria A, B, C
Display the result in section - A, section -B, and section-c as the HTML output.
Now in MVC I am doing the following
Get the list of building in the database on building_data (model)
Store the result from building_data in a $data array of the building controller
Split the results based on criteria A,B,C in building_view and output the HTML (can i do the condition based classification of data (without using mysql queries) in view ? !My actual question)
Am I doing the right thing here without violating MVC architecture rules ?
MVC is a design pattern. Not an architecture.
But, if you are looking to learn best practices or MVC, then CodeIgniter is the wrong choice. It is filled with bad and outdated practices (PHP4 code fragments, global state and many other issues), and is not implementing anything even close to MVC pattern. It is more like a bad Rails clone for PHP.
Views are supposed to be objects, and not dumb templates. Your controller should tell model layer which building the user has selected, and then view acquires the details about current building and decides how to represent it all.
In proper MVC implementation, views are instances which contain presentation logic. They acquire information from model layer and then choose which templates to use for rendering the response or even if a HTML response is necessary. Maybe user actually requested data in JSON or XML format. Or maybe the only response, that view needs to send, is a HTTP header.
Also you should be aware that you cannot implement classical MVC pattern in web application (or at least it is extremely difficult and entails use of sockets and persistent model). Instead we use MVC-inspired patterns. The main difference between them is way how View gets to the information from Model layer.
in MVP and MVVM patterns the view is passive and receives data through controller-like structure (presenters or viewmodel, perspectively).
in Model2 MVC and HMVC patterns the view is active, it requests information directly from model layer.
Also there is third group: Rails-like implementation. It replaces model layer with collection of ActiveRecord based ORMs, pretend that view is a template, and "controller" is combination of presenter and view responsibilities.

MVC architecture and weakly typed languages (for instance PHP) Is model unnecessary?

Shouldn't models just describe data that will be passed from a controller to a view? Doesn't that make models unnecessary in weakly typed languages? In PHP, they are doing DB work in models, but isn't that wrong? As I see it, models are just unnecessary in weakly typed languages...
There are some misconceptions about the term model. Microsoft's MVC3 framework has the concept of a view-model, which is simply the data you use to render your views. This isn't however what the M stands for exactly in MVC. The model includes your business entities. We have thin controllers and fat models, but very thin view models. Our controllers make calls to services that perform business logic, and the controllers never do this logic themselves. We then translate our business entities (our data models) and convert them into a lightweight view model, which can be used for rendering a view.
So to answer your question
Shouldn't model just describe data that will be passed from controller to view?
Then perhaps what you are really asking is aren't view-models unnecessary? I'm not sure why you think this. View model + view makes the result. In PHP it can be helpful to define a class with easily accessible properties on it. This is just sensible for clarifying your expectations and prevents you from calling methods with hideously long sets or arguments. In JavaScript there is no need to define a view model as such, you just push the properties onto a new object and pass it along with your view to your view rendering logic. This is more a reflection of the OO pattern these languages use and not the fact that they are weakly typed.
If you are asking if model is unnecessary, then you have missed the purpose of the MVC architecture. A big part of MVC is that you separate your concerns. Why apply any architecture to your code? I am sure you can find a better explanation of the motivation behind MVC than I can give you.
A model is a useful conceptual tool, even if it's not strictly necessary in PHP to separate it from the DB code e.g. you can have a data object associated with each table that encapsulates some business logic, or define a set of business entities that aggregate the data across tables into domain-specific objects that the controllers can then use, or just have one monster DB object that has all the access functions and returns the entities. This has definite advantages over having DB code directly in use by the controllers:
If you are defining complex data structures that run across DB tables, you don't want to do that in controller code due to the risk of duplication - far better to have a single definition that enforces consistency across the system. Although this can introduce dependencies, having one function/object that defines that data makes it easy to find out where the data is used so you can fix things.
Third party maintenance is far easier if there's one place to go to where all the data structure definitions are found.
It makes unit testing easier if you can swap out the whole model or parts of it and replace it with mock object(s) that will provide test data
It makes controllers lighter and therefore more readable and maintainable
So you could argue that it's not necessary, but it helps a lot.
I've always seen models as a tool to provide data. That means that your controller doesn't ever have to worry about the data source, and if you want to switch from using a database to XML files then you only have to swap out your model.
So long as you have some data provider abstraction. Some Models will do low level validation (tightly coupled to the storage engine - null checks etc) but the controller "should" do all of the business logic/validation.
I personally have a thin struct like class that is mapped to each table (all implementing IDataStruct). This struct, or a collection thereof, is the only thing that moves between the DomainObject and the DataProvider. I can then enforce via my interface what datastruct I should be receiving. This is not a silver bullet but I have found it to work well (Makes things like caching and unit testing quite easy)
I hope this hasn't confused the issue.

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.

Categories