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.
php mvc
Moderator: General Moderators
Re: php mvc
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:
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
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:
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.
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>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>
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>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.