1

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?

Uchiha Obito
  • 69
  • 1
  • 9
  • But without the models. Why don't you call it VC then? – hakre Aug 07 '12 at 21:38
  • 3
    **Don't do this**. You're defeating the entire point of MVC. Controller logic doesn't go in the views. – user229044 Aug 07 '12 at 21:39
  • @hakre - I call it LVC (Library, View, Controller) for now. And meagar - I read a lot about Models but I just don't get it. Why use models when I have controllers? Just more code .... But I'm sure that if I learn how to use controllers and views, I will learn how to use Models too. – Uchiha Obito Aug 07 '12 at 21:41
  • What is the code in View's render method? – Chris Trahey Aug 07 '12 at 21:44
  • @ctrahey - added to main post – Uchiha Obito Aug 07 '12 at 21:45
  • 1
    I guess we have reached the point when MVC stands for "My Very Code". – tereško Aug 07 '12 at 21:50
  • @MichałKról: Throwing terams against the wall to shuffle them and then just picking the first letter of each is great for making jokes but counter-productive if you actually want to discuss design topics. Then use your own wording, but don't invent a paradigm because of understanding problems. Will bring you more further, use your language, it's a tool. – hakre Aug 07 '12 at 21:51
  • :/ Just tell me what none of the tutorials I read didn't - Why do you need Models when you have Controllers? Models have functions. Controllers too. Controllers call Models. What's the point? – Uchiha Obito Aug 07 '12 at 21:55
  • The model represents your dynamic data - blog entries that are stored in a mysql database for example. By separating the model logic from the controller logic, you can reuse the same model in different controllers. – Pierre Aug 07 '12 at 21:58
  • Ok, but I don't have any dynamic data yet... I thought I can accomplish http://localhost/controller/function/value with what I'm doing :( – Uchiha Obito Aug 07 '12 at 22:00
  • @MichałKról: That's okay, but more a so called Frontend or Application Controller. You do not need any MVC for that at all. http://martinfowler.com/eaaCatalog/applicationController.html ; http://java.sun.com/blueprints/patterns/FrontController.html – hakre Aug 07 '12 at 22:04
  • If you don't see what the models are for then you've missed the whole point of MVC. A controller is supposed to be an extremely simple thing, all it should do is pass user input to the model(s) and collect the results for presentation to the view. It should do no real work – GordonM Aug 07 '12 at 22:04
  • @GordonM - Hmm, ok, it clears my point of view about models a little. I will read more and try again with modified code – Uchiha Obito Aug 07 '12 at 22:11

4 Answers4

4

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:

Community
  • 1
  • 1
tereško
  • 58,060
  • 25
  • 98
  • 150
  • I don't care about the terms, I just want to display /controller/function/value from link, and I've been told that's what MVC is for :/ – Uchiha Obito Aug 07 '12 at 22:03
  • @MichałKról , do not confuse [routing of request](http://stackoverflow.com/a/9855170/727208) with MVC pattern. They are separate things. Routing happens before your code *hits* the MVC triad. – tereško Aug 07 '12 at 22:20
4

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:

  1. Model- This is where your data is stored.
  2. View- This is how your data is represented to a user.
  3. 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:

enter image description here

  1. 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.
  2. 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.
  3. 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.

csalvato
  • 490
  • 5
  • 13
2

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
0

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..

raidenace
  • 12,789
  • 1
  • 32
  • 35
  • Ohhh, that explains a lot. Thank you. So the controllers have functions (methods) to process the requests, not to be used in (for example) front end. I get it :D – Uchiha Obito Aug 07 '12 at 22:12
  • The controller is like the duct tape that holds it all together, the model doesn't care about anything than having all the functions you need for core functionality of your app - like get value from db, to db, send email, process forms etc etc..and the view, should only try to render the data the controller gives it (which it got from the model).Hope my explanation did help you get an idea of MVCs.. – raidenace Aug 07 '12 at 22:21
  • @Raidenace: How do you explain the term *View-Model* in your world? – hakre Aug 07 '12 at 22:45
  • @hakre: I do not get your context, are you asking about View-Model in terms of viewpoints/MVVM or are you asking about their specific relation within an MVC? – raidenace Aug 08 '12 at 01:06
  • In your answer it sounds like that there is not much difference between library and view. As you wrote that library is a model, it looks like you're equally saying that view is a model, too. So I was asking about how you would related view and model in the world you outline in the answer (as you already break with common MVC definitions I didn't expect you to now adhere to even more differentiated MVC paradigms like MVVM etc.) – hakre Aug 08 '12 at 01:11
  • I think you misconstrued what I posted.My only intention was specifically to give Michal some insight on why it is not really a good idea to write too much code into the controller and instead to have them deflected into models/libraries/helpers - whatever you want to call them. And I was NOT aiming at a purist answer at all. And there IS no purist answer btw. Also I do not see how `it looks like you're equally saying that view is a model, too`..maybe you can help me understand why you felt so? – raidenace Aug 08 '12 at 01:19
  • Since when is the view *not* a library? – hakre Aug 08 '12 at 10:41