php mvc

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
darkpoetry
Forum Newbie
Posts: 1
Joined: Wed Sep 16, 2009 2:41 am

php mvc

Post by darkpoetry »

I know php mvc frameworks already exist however for my own knowledge i want to know how to code a basic php mvc framework of my own.

i feel that this would allow me to understand things better.
i have Google-d around a bit but the tutorials I came across contained errors at important steps.

can anyone point me to any good resources ?

- thanks

note - if the tutorial does not have .htaccess help that's alright - i have that part sorted.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: php mvc

Post by requinix »

MVC is just a principle. It can apply to many things, of which a framework is just one.

Wikipedia on MVC

For an MVC framework there are a couple things to pay attention to:
- A specific way of handling data in a database. This isn't actually a requirement (the model could be implemented by non-framework code) but some sort of abstraction layer is generally a good idea.
- A specific way of separating the PHP logic from the HTML output. For instance, look at this:

Code: Select all

<?php session_start(); ?>
<html>
<head>
<title>Page title</title>
</head>
 
<body>
<p>Here is a list of numbers:</p>
<p><?php $numbers = a_list_of_numbers();
foreach ($numbers as $n) echo $n, " "; ?></p>
</body>
</html>
The logic behind the PHP code is right there in the middle of the HTML. First step is to move the non-HTML part out of it, like

Code: Select all

<?php
 
session_start();
 
$numbers = a_list_of_numbers();
 
?>
<html>
<head>
<title>Page title</title>
</head>
 
<body>
<p>Here is a list of numbers:</p>
<p><?php foreach ($numbers as $n) echo $n, " "; ?></p>
</body>
</html>
 
You can't move all PHP code - it has to display something - but the call to a_list_of_numbers() can be moved earlier on in the code.

Now imagine you had two files:

Code: Select all

<?php // file1.php
 
session_start();
 
$numbers = a_list_of_numbers();
 
include "file2.php";

Code: Select all

<?php // file2.php ?>
<html>
...
</html>
That's the controller in file1.php and the view in file2.php. The advantage is that if someday you decide to make an RSS feed of those numbers, you just make a second view - the controller stays the same.

What a framework would do is
- Figure out what code should be executed
- Execute it
- Figure out what view should be rendered
- Render it


Consider downloading a framework (a CMS, Zend, Cake, etc) and seeing how it works.
Post Reply