Php – MVC View Question

mvcPHPweb

In my PHP web page (index.php), I have a simple script that calls a "page" class, and then builds the page from it.

Index.php executes methods within an instance of the 'page' class, such as "add_to_body("bla bla bla")". It can then call a "build()" method, where the page class will return a string with the user input and some other HTML elements pre-added in, that index.php can echo. Essentially the page class is a template of sorts.

I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller?

Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)?

Many thanks for your help!

Best Answer

generally the idea with a "View" is that its as 'dumb' as possible. it has the bare minimum of code to display the page. the "Model" is typically the methods talking to a database, validating data, creating and returning data structures - object, array, etc. the "Controller" is in the middle of the View and the Model.

so like if you have a contact form - the controller tells a model to validate the form data and add it to a database. if the model comes back with "validation failed" - the controller says - show this form again - and passes relevant data to relevant view. or if the model says "new contact added" - the controller says - show the thank you page.

when you are comfortable i would suggest taking a look at a basic php framework like codeigniter. it can make it easier to see how the MVC parts relate to each other.


response: the view should be separate file, and there should be separate view files for different needs. remove as much logic as possible from view files. this means you will end up having more files, but otherwise your view file "Knows" too much about your application. classic example is having some kind of check in a view file if the person looking at it has admin privileges. the view file should not know this. just make separate files.

in a small application you can combine controller and model in same file. and that is a good way to start - build out your application, and then as the methods become clear, you refactor the methods from the controller - into your models.

i would hasten to add that you should learn a php framework like codeigniter, even if just to see examples of MVC. the framework gives you a good starting place and you can also look at other peoples applications.

Related Topic