Simple PHP MVC approach
Thousands of words do not compete with pure example, so here is a simple example:
Imagine that you want to display a page describing a “car” (including a “car identifier”) with an imaginary car seller: http://example.com/car.php?id=42 )
Basically, you can structure your code using a hierarchy, for example:
Configuration directory (this is not part of the MVC architectural pattern):
+ config/ - database.php <?php return new PDO("mysql:host=localhost;dbname=database", "user", "password"); ?>
Folder for your document root (scripts acting as controllers ):
+ htdocs/ - car.php <?php require_once 'CarService.php'; $carService = new CarService(require 'config/database.php'); $car = $carService->getInformationById($_GET['id']); require 'car.tpl'; ?>
Folder encapsulating the whole Model (tooltip: "Thin controllers, Fat model"):
+ model/ - CarService.php <?php class CarService { protected $database; public function __construct(PDO $database) { $this->database = $database; } public function getInformationById($id) { return $this->database->query( "SELECT model, year, price " . "FROM car " . "WHERE id = " . (int) $id )->fetch(); } } ?>
The last folder containing all of your Views (/ templates):
+ views/ - car.tpl <html> <head> <title>Car - <?php $GLOBALS['car']['model'] ?></title> </head> <body id="car"> <h1><?php $GLOBALS['car']['model'] ?></h1> Year: <?php $GLOBALS['car']['year'] ?> Price: <?php $GLOBALS['car']['price'] ?> </table> </body> </html>
What is it.
For completeness
You may notice the use of $ GLOBALS in templates, it can be a convenient coding standard for denoting local template variables from those that you get from the "controller".
In order for the above code to work, you will need PHP to configure:
include_path="/the/path/to/model:/the/path/to/views"
Go further
Good URLs
you may need good urls if you are using apache you can achieve this with
RewriteEngine On RewriteRule ^/car/([0-9]*)$ /car.php?id=$1 [L]
This allows you to record URLs such as http://example.com/car/42 that will be internally converted to http://example.com/car.php?id=42
Reusable patterns
Being PHP files, nothing prevents you from creating headers.tpl, footers.tpl, menu.tpl, ... which you can reuse with include () / require () to avoid duplication of HTML.
Conclusion
This is very similar to what Rasmus Lerdorf said: http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html .
Remember that MVC remains an (n) (architectural) pattern . Software templates are reusable principles for solving common problems, if they are reused by code , they would be called "libraries" instead.
Frames such as Zend Framework, Symfony, CakePHP, etc., offer a framework for adopting the MVC approach, but cannot enforce it, since MVC is an architectural pattern that needs to be learned and understood whether you are using an existing framework or not.