PHP - Functions from the controller in view - php

I'm trying to learn MVC pattern, (but without the models because I don't see for what I can use them when I have the controllers).
So I want to display some content in my view. How do I do that?
This is my controller that takes care of index:
<?php
class Index extends Controller {
function __construct() {
parent::__construct();
$this->view->render('mainpage/index');
}
public function wynik($arg) {
echo $arg;
}
}
$klasa = new Index();
?>
And I want to call the function wynik($arg) in my view. How can I do this? My Controller library looks like this:
<?php
class Controller {
function __construct() {
$this->view = new View();
}
}
?>
And in views/mainpage/index.php I'm trying something like this:
<?php
echo $klasa->wynik('abc');
// tried this too:
$this->wynik('abc');
?>
But it doesn't work:
Notice: Undefined variable: klasa in C:\wamp\www\lvc\views\mainpage\index.php on line 2
and
Fatal error: Call to a member function wynik() on a non-object in C:\wamp\www\lvc\views\mainpage\index.php on line 2
This is View library:
<?php
class View {
function __construct() {
}
public function render($name, $noInclude = false) {
if ($noInclude == true) {
require 'views/' . $name . '.php';
} else {
require 'views/header.php';
require 'views/' . $name . '.php';
require 'views/footer.php';
}
}
}
?>
I was thinking - yeah, it searches for wynik() function in View() class, that's why it errors. I want the view to search through functions in my controller. How can I do this?

This code example is not working because the variable $klasa does not exist when you are trying to reference it. The initialization of the object done by calling "new Index()" must be completed first, then that value will be assigned to $klasa. Thus, your code is trying to access $klasa before it exists.
That said, I wouldn't continue to debug this problem. You are missing the point of MVC entirely, and until you understand it, you will not be able to code a controller and view that work well together. Spend time understanding MVC, not by implementing it yourself, but by using another system as an example.
If PHP is your flavor, try the Yii, CodeIgniter or Symphony Frameworks. If you like Python, try Django. If you like Ruby, try Rails. If you like C, learn Objective-C and try iOS.
The MVC model is very simple:
Model- This is where your data is stored.
View- This is how your data is represented to a user.
Controller- This is what your view talks to, so that it can act on the model.
Let's use a simple ice cream vending machine as an example. Assume the vending machine is one of those machines is like this one, where you can't see the items:
Model- The ACTUAL ice creams stored in the back. Lets say, 4 chocolate, 1 strawberry, 3 vanilla. The view and controller don't care how much of each ice cream are there. It is the model's job to keep track of that and make sure we don't have negative ice creams in slots, or other things that don't make sene, for example.
View- These are the little buttons showing what ice creams exist as choices. The view doesn't know or care how many ice creams are in the back, or what ice creams even exist. It simply shows the user something relating to the model, and it doesn't care what is in the model or how the model is structured.
Controller- When a user interacts with the view (that is, they push a button) the controller will take that input and run it by the model. The controller doesn't care how the model is structured, it doesn't know what is back there. All it knows is "When a user presses a button, I need to use the data in the model to make a decision based on that input". For example, when the user presses on a valid item that is in stock, the controller takes that input, runs it by the model, sees that it is ok and dispenses an ice cream. When the user presses on an invalid item that is not in stock, the controller takes that input, runs it by the model, sees that it is out of stock, and tells the view to display an error.
If you get this basic concept down, MVC as a whole will make a lot more sense and speed up dev time dramatically. Understanding MVC is probably one of the more important things for a budding web/mobile developer right now, as most popular web frameworks are based on it (Django, Rails, Yii/CodeIgniter/Symphony), as well as iOS.

MVC is a design patter which combines two layers:
Model layer
Presentation layer
If your application does not have model layer (which contains all the domain business logic), then there is no MVC.
Presentation layer is made mostly from two groups of structures: views and controllers.
controllers : responsible for reacting to user's input and, based on that, changing the state of model layer and view.
views : responsible for the display(or presentation) logic, based information, that view has received from model layer. Based on this information views choose to appropriate response - it can be either just a HTTP header or HTML file, rendered from multiple template or formated JSON/XML data.
But you do not really have Views either. What you call "view" is actually are simple PHP templates.
As for the view accessing controller's methods, it is against all the principles in MVC and MVC-inspired patterns. View is a separate entity, which acquires data from model layer and has the state changed by controllers.
In classical MVC and Model2 MVC patterns the view is active. It requests the information directly from the model layer. Whereas in MVP and MVVM patterns the view is passive and information from model layer is provided by controllers (though in these patterns they are called "presenters" and "viewmodels" respectively).
Views do not use controllers.
Please, do some research before you start throwing terms around just because you think, that it is the latest thing.
Read the following materials:
GUI Architectures
MVC in PHP part 1: Hello World
Model-View-Confusion part 1: Why the model is accessed by the view in MVC
A Description of the Model-View-Controller User Interface Paradigm in the Smalltalk-80 System
How should a model be structured in MVC?

Instead of MVC and not really knowing why and so on, I suggest you another concept called Transaction Script that also work very well with a Frontend Controller or an Application Controller.
Working with Transaction Scripts allows you to get more familiar with OOP while you also benefit from some application structure without the overhead and problems that a misunderstood MVC does carry.
For example within a transaction script object, everything can access the functions of that a transaction. Your libraries, your view and everything else (the model).
Then you will see things growing. But forget Codeigniter and similar, write this from scratch (don't mimic things), you'll learn more and you will have more efficient code.
And you will have it your way, which is great for learning.
For the libraries, just fetch stuff from the Packagist and Pear repositories you will not have many wishes left.

I am not going to add code samples here, but I hope what I say will help you look in the right direction. LVC (Library, View, Controller) is just you changing one name(Model) to another (Library) Doesnt really matter at all, you are still using MVC, you just happen to call your Model a Library. This is a vast topic, but I am only trying to make you see the use of having models and offloading code into that instead of in controllers.
The way to look at it is like this:
Typically controllers should only perform following - check requests, invoke Model(In your case Library) methods, which process those requests, and take those results and pass to the view to render. Think of each function in a controller to be an endpoint URL that the user can type in the address bar and access.
Think you have a function like profile($user_id) in a controller called user, to show user profile and the user accesses it using the url www.mydomain/user/profile/1234.This is all very fine. But what happens if you start throwing in all kinds of utility functions inside this controller like say, strip_all_zeroes(). It becomes bad if the user can access this using mydomain.com/user/strip_all_zeroes, right? It might start throwing all kinds of warnings,errors, or even expose sensitive data..That is where models come in. They can be used to create all kinds of helper functions, whole data classes as required..
Of course this is very broad, over-simplified and not totally accurate, but I hope you get the idea..

Related

Basic MVC (PHP) Structure

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.

Implementing MVP in Web Applications

As I understand it, MVP is a derivative of MVC where the Model and the View are loosely or completely decoupled, and the Presenter replaces the Controller and acts as the bridge between the View and the Model. This pattern seems more appropriate than traditional MVC in web applications (whether or not that is true is not the subject of this question, so please refrain from going down that direction).
My problem is in implementing the various MVP pieces in PHP, using a passive view. Here is my current flow of things:
The PHP script sets up an autoloader and a router. To me, this means whatever view was in existence send an event of some kind to the server.
The router then determines which presenter should be used based on the request.
Here be dragons. The Presenter acts as the bridge between the View and the Model and should take a View and a Model as dependencies so it can easily be tested. That means I need to know what model and view I should be using before the presenter is created.
The presenter seems to be the class that knows what Model and what View it needs, so how can I move that logic out of the presenter? I understand that the generic pattern to use is a factory, I just can't seem to understand how to implement it in this case.
Perhaps I am doing this all wrong. Maybe I've been coding for too long of a stretch and am experiencing mind warp. Regardless of why I can't seem to understand how to solve this problem, I'll accept any guidance.
Not 100% sure I know what you're asking. You are right that you load the appropriate controller based on the request. That controller is typically associated with a model and a view.
Let's say you have a URL that looks like: http://www.example.com/test/view/1
It would be fairly standard to load the Test controller, call the method view pass it the argument 1. So let's assume you have:
TestController.php
TestModel.php
test.php (view)
When the TestController loads it includes the model, TestModel, where your "data stuff" goes (I think you understand that). So for this example, let's say view wants to load the last 5 posts from the user with id 1. So in TestController.php:
function view($arg)
{
$userID = $arg;
$posts = $this->model->loadPosts($userID);
$this->render('test', $posts); // outputs the HTML in test.php
}
And in test.php, you can loop through $posts and output it however you choose.
It seems like you already know how this stuff works though, which is why I am confused as to what you're asking. Does this clear up anything?
I find it useful to think of Web Apps in terms of states and state transitions. the application is in a particular state, it's "at" a View, some HTML was with the aid of the associated Presenter from data in the Model and rendered to the browser . The user takes an action and this is going to move our app to a new state. So we are moving from one View/Presenter pair to another. In my mind the Model is a longer lived, evolving thing, I don't see us getting a new Model for each transition.
So you have PresenterA, responsible for responding to events in ViewA.
PresenterA receives some event, performs some work that may result in Model changes, and then decides which View to go to, say ViewB. ViewB can create its Presenter. As per the Wikipedia example (not PHP I realize, but the principle is clear):
public class DomainView: IDomainView
{
private IDomainPresenter domainPresenter;
public DomainView() // Constructor
{
this.domainPresenter = new ConcreteDomainPresenter(this);
}
}
In effect the Presenter is the creator of the next View/Presenter pair. If you have more complex logic replace the explicit constructor
new ConcreteDomainPresenter(this);
with a factory, working with View and Model information.

Do I finally get MVC?

Given the URL http://www.example.com/products.php
products.php contains:
<?php
include ('model.inc');
$controller = new Controller;
class Controller
function __construct()
{
$model = new Model;
$this->model->model_methods();
include ('view.inc');
}
}
?>
model.inc contains:
<?php
class Model {
// methods that return data
}
?>
view.inc contains:
<html>
<head>
</head>
<body>
<!-- html plus php output -->
</body>
</html>
So products.php creates the controller. The controller creates the model, figures out what to do and manipulates data only through the model's methods, and finally turns things over to the view. The only php in the view is to output data or to loop through an array to output data.
I've been playing around with a few lightweight php frameworks that implement MVC, but so much of the magic gets done backstage that I don't know if I finally get it or not. :)
Have a look at this MVC article on Coding Horror.
If you think about what a model represents - a "model" of the data, or a subset of the data - and about what the view represents - a particular "representation" of the data - then it's easy to understand that these two entities require something to route the information between them. Hence, the controller. The flow should be M -> C -> V
A good test if you "understand" MVC (and thus, if your application is MVC) is "Can I skin my application?" If you can think of an easy way to apply different skins and styles to your data seamlessly, then you have succeeded in separating the model from the view, and your controller is effective at what it does.
Although I don't know how it's actually implemented, I'd argue that StackExchange is a great example of the MVC idea. There are multiple sites dealing with multiple topics, but they all have very similar kinds of "models" - very similar data. The presentations - the views - are free to change as they please, and the controller is there doing all the logical heavy-lifting. This may be kind of a contrived example, but I think it works conceptually, if not technically.
Personally, I think your Controller is responsible for too much. Instantiating the Model and View inside the Controller "feels" wrong. The Controller should only be responsible for getting data from Model and giving it to View. Right now the Controller is responsible for creating the Model AND it is effectively acting as the View by including the HTML.
The important part here is that each object has, ideally, a singular responsibility.
Model = the data holding your app (this is really a layer instead of an object)
View = the final output sent to the user
Controller = give stuff to View from Model
I recommend you create some kind of "front controller" type object that handles the appropriate instantiation of objects and is the one responsible for setting up all the different pieces.
Ah, ok, but how does the controller "give" the data to the view?
Well, this is really gonna be dependent upon the precise architecture your particular implementation uses. MVC goes far beyond a simple design pattern and can be interpreted in a variety of ways. I prefer something that looks like...
class Controller {
protected $viewData = array();
public function index() {
$data = $this->Model->getData();
$this->giveToView('data', $data);
}
public function getViewData() {
return $this->viewData;
}
protected function giveToView($key, $value) {
$this->viewData[$key] = $value;
}
}
So, the Controller is still getting the data from Model but now instead of including a view file we just store the data and let a different class take care of actually rendering the output.
class View {
protected $viewData;
public function setViewData(array $data) {
$this->viewData = $data;
}
public function renderViewFile($filePath) {
// from example the variable $data is now available in this scope
// to include the $filePath
extract($this->viewData);
include $filePath;
}
}
Obviously this is a simplified example but the basic premise stays the same.
The idea of the MVC is to separate your application logic (business logic, business tier, middle layer or middle tier), input (url, post data, get data) and output (UI - the html in your case).
It is an determined as architectural pattern (software architecture). It is not matter of code but of ideologic for building applicaions.
Read here: MVC in Wikipedia
I would prefer CodeIgniter - a very static collection of functions, some named Model other Controller and there are Views plus a lot of utilities, allowing you to concentrate on the application logic and the layout, without loosing coding freedom in PHP (seems you use PHP). Unless you find out that it's not fitting, but that can happen with any framework.
Yes. This is more or less MVC. The basic gist of MVC is as follows:
Controllers tie your models and views together and normally take care of passing model data to the view.
Models handle your business logic.
Views handle presentation and presentation related logic.
I'd definitely take time to learn PHP MVC framework such as Kohana, Lithium, Symfony, or Cake as they all provide a ton of utilities to make your life easier. They can also handle automatic routing wich makes your URLs cleaner, and helps abstract URLs from their direct connections to controllers.
Kohana: http://kohanaframework.org/
CodeIgniter: http://codeigniter.com
Lithium: http://li3.me/
Symfony: http://www.symfony-project.org/
Cake: http://cakephp.org/
Not quite yet!
The /products.php portion is generally abstracted. The file name is matched in a router during execution, which matches it to a corresponding controller. In this case, you could have a Products controller by name, but you could match (via routing) a things.php request to the Products controller.
There's generally some more execution/initialization "magic", which calls the pertinent model/view based on the request - for example, it would take /products.php, change to Product, and look for a model, controller, and view named Product.inc
Yes, that is the essential basis of the MVC pattern. The controller can be thought of as the brain which figures out what action to take. Depending on that action, it may communicate with models to get the necessary data to render the view. It then makes the necessary data available to the view and renders the HTML for the browser.
MVC at it's most basic definition requires that you split the navigation logic, the data logic and the presentation logic into 3 parts. There is no special structure to observe as long as you have the parts split so that you can easily interchange and isolate your code.
Obviously, there are many more topics to cover if you want to be an hardcore MVC layout.
For example
Splitting your application into folders called controllers, views and models
Creating a good data layer to simplify your models as much as possible
Integrating a helper/widget logic so you can reuse visual components
Integrating a routing engine with mod_rewrite to create clean urls
Those are just a few of the items you should cover to get a real good MVC layout. But then again... MVC is a design pattern, it's a way of doing things without being something totally concrete or concise.

PHP MVC: Do i really need a Controller?

My question is simple but (I guess) hard to answer:
Do I really need a complete Model-View-Controller design pattern in my PHP Website / Web-App?
I can't understand how a Controller could be useful with PHP since every PHP site is generated dynamically on every request. So after a site is generated by PHP, there is no way to let the View (the generated HTML site in the Browser) interact with the controller, since the Controller is on the server side and generated once for each site request, even if the request is AJAX...
Do I understand something completely wrong?
Why should I use any kind of MVC PHP Framework like Zend or Symphony?
EDIT:
For example lets assume, there should be a website to represent a list of customers in a table:
My Model would be a simple Class Customer on the server side that queries the database.
My View would be the generated HTML code that displays the Model (list of Customers).
And the controller? Is the controller only evaluating the GET or POST to call the correct method of the model?
Do I have understand something completely wrong?
Yes.
The MVC pattern is not for the browser. The browser sees HTML anyways. Whether this HTML is generated with C++, PHP, Java or whatever it doesn't matter. The browser doesn't care what design patterns were used to generate this HTML.
MVC is a design pattern to organize and separate responsibilities in your code. So it's not for the browser, it's for the developers writing the code. It's to create more maintainable code where you have a clear separation between your business logic (Model), the communication between the model and the view (Controller) and the UI (View).
Whether you should use the MVC pattern in your web site is a subjective question that I prefer not to answer as it will depend on many factors.
Short Answer
Yes. A controller will be responsible for preparing data to display for rendering and sometimes handle GET and POST requests that originating from your client. It should leave HTML generation to the view.
Long Answer
MVC can be very helpful in keeping applications maintainable and your code base sane. The pattern helps ensure separation of concerns of your code and in most cases will steer yor clear of 'spaghetti php' where your application logic is tangled with the HTML generation. A sample MVC setup below (there are sure to be many variations of this, but it gives you the idea):
Model
Responsible for fetching data from the database and saving changes when requested. One example might be a php object that represents a user with name and email fields.
Controller
Responsible for massaging and manipulating data and preparing it for display. The prepared data is passed to a view for rendering, with the view only needing to be aware of just the data it needs to render. For example: a controller may look at a query string to determine what item to fetch to render and combine this with several additional model queries to get additional data.
Often controllers will also be responsible for handling GET and POST requests that originate from your HTML client and applying some sort of manipulation back on your database. For example - handling form submits or AJAX requests for additional data.
View
The view is responsible for actually generating the HTML for display. In PHP, a view would often be a template file with minimal logic. For example, it might know how to loop over items provided to it from the controller or have some basic conditionals.
Application MVC vs PHP/Python/etc. MVC
From your other comments it sounds like you are familiar with using MVC in the context of a desktop or mobile application.
One of the main differences between MVC in the two is the granularity at which the controller is manipulating the view and responding to events.
For example, in a traditional application the controller might listen for click events originating from a button and respond appropriately.
When your doing server side html generation however, your controller is only 'alive' for a brief moment while its preparing html to ship out over the wire. This means that it can only do so much to setup and prepare the view for display.
Instead of listening traditional events from the UI, it can instead react in different ways to future GET and POST requests. For example, you may have a "save" button on a form trigger a POST request to your server (such as yourpage.php?action=save&value=blah). While handling this request your controller might access your models and apply changes, etc.
I realise that I am answering a very old questions, however, I do not believe that any other question has answered your initial concern appropriately, and this will hopefully add something useful for others who may stumble across this question in their learning about MVC.
Firstly, I will start by saying I read an interesting article about the confusion which exists within the PHP community about MVC and it is worth a read if you are asking this type of question.
Model-View-Confusion part 1: The View gets its own data from the Model
Secondly, I do not believe you have misunderstood anything at all, rather you have a better understanding of PHP and MVC which is allowing you to ask the question. Just because something has been defined and accepted by the community at large, it does not mean you should't question its use from time to time. And here is why.
There is NO memory between requests (except for SESSION state) within a PHP application. Every time a request is received the entire application fires up, processes the request and then shuts down i.e. there are no background application threads left running in the background (at least none which you can use within your application) where you could, theoretically, maintain application state. This is neither good, nor bad, it is just the way it is.
Understanding this, you can probably start to see what you are thinking is correct. Why would a View (which is allowed to access its own data from the Model) need a Controller? The simple answer, is that it doesn't. So for the pure display of a Model, the View is perfectly entitled to fetch its own data (via the Model) and it is actually the correct way to implement MVC.
But wait. Does this mean we don't need Controllers? Absolutely NOT! What we need to do is use a Controller for its appropriate purpose. In MVC, the Controller is responsible for interpreting user requests and asking the Model to change itself to meet the users request, following this, the Model can notify it's dependencies of the change and the View can update itself. Obviously, as you know, in the context of a PHP web application, the View is not just sitting and waiting for update notifications. So how can you achieve the notification?
This is where I believe MVC got hijacked. To notify the View it's Model has changed, we can simply direct them to the URL of the View which accesses the now updated Model. Great, but now we have introduced something into the Controller. Something which says, "Hey, I'm a controller but now I have knowledge of the location of the View." I think at this point, someone thought, "why do I bother redirecting the user? I have all the data which the View needs why don't I just send the data directly to the View?" and bang! Here we are.
So let's recap.
A View CAN access the Model directly within MVC
The Model houses the business logic for the Domain Objects
A Controller is not meant to provide the View access to the Model or act as any type of mediator
The Controller accepts user requests and makes changes to it's Model
A View is not the UI/HTML, that is where a Template is used
A practical example
To explain what I have been describing, we shall look at a simple, commonly found function within most websites today. Viewing the information of a single logged in user. We will leave many things out of our code here in order to demonstrate just the structure of the MVC approach.
Firstly lets assume we have a system where when we make a GET request for /user/51 it is mapped to our UserView with the appropriate dependencies being injected.
Lets define our classes.
// UserModel.php
class UserModel {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
public function findById($id) {
return $this->db->findById("user", $id);
}
}
// UserView.php
class UserView {
private $model;
private $template;
private $userId;
public function __construct(UserModel $model, Template $template) {
$this->model = $model;
$this->template = $template;
}
public function setUserId($userId) {
$this->userId = $userId;
}
public function render() {
$this->template->provide("user", $this->model->findById($this->userId));
return $this->template->render();
}
}
And that's it! You do not require the Controller at all. If however you need to make changes to the Model, you would do so via a Controller. This is MVC.
Disclaimer
I do not advocate that this approach is correct and any approach taken by any developer at any point in time is wrong. I strongly believe that the architecture of any system should reflect its needs and not any one particular style or approach where necessary. All I am trying to explain is that within MVC, a View is actually allowed to directly access it's own data, and the purpose of a Controller is not to mediate between View and Model, rather it is intended to accept user requests which require manipulation of a particular Model and to request the Model to perform such operations.

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