MVC has a number of connotations, but is often implemented with a Front Controller in PHP. In fact I think the Front Controller is probably the solution of choice for most enterprise type PHP coders. Here is an example:Gambler wrote:MVC requires you to load and parse code for all methods in a class. So if you have contoller with 40 methods, you're parsing 40 methods, while using only one. I think, that's what xcom923 is talking about.Why not just use a basic MVC pattern?
Code: Select all
<?php
class FrontController{
var $action_dir;
var $default_action;
var $error_action;
var $action_param;
var $action = '';
function FrontController($action_dir='action', $default_action='home', $error_action='error', $action_param='action'){
$this->action_dir = $action_dir;
$this->default_action = $default_action;
$this->error_action = $error_action;
$this->action_param = $action_param;
}
function & commandFactory($action){
$obj = null;
$filename = $this->action_dir . $action . '.php';
if (file_exists($filename)) {
include($filename);
if (class_exists($action)) {
$obj =& new $action();
}
}
return $obj;
}
function execute(){
if (isset($_GET[$this->action_param])) {
$this->action = preg_replace('/[^a-zZ-Z0-9\_\-]/', '', $_GET[$this->action_param]);
} else {
$this->action = $this->default_action;
}
$obj = & $this->commandFactory($this->action);
if (! $obj) {
$obj = & $this->commandFactory($this->error_action);
}
$obj->execute();
}
}
?>A Front Controller accepts URL in to form "www.mysite.com/controller.php?action=home" or if it in index.php just "www.mysite.com/?action=home" or with clean URLs it might be "www.mysite.com/home/".
Here are the other files (if you dump them all in a directory you should be able to see them work by passing various "?action=" params like 'home', 'page' or ''):
index.php (or some other name like controller.php)
Code: Select all
<?php
include 'FrontController.php';
$fc =new FrontController('./', 'home', 'error');
$fc->execute();
?>Code: Select all
<?php
class home{
function execute(){
echo 'Home';
}
}
?>Code: Select all
<?php
class error{
function execute(){
echo 'Error';
}
}
?>Code: Select all
<?php
class page{
function execute(){
echo 'Page';
}
}
?>This code really should be expanded with a little better error handling, maybe plugabble Action Factories, Request and Response objects, etc. And adding a Service Locator object, that gets passed everywhere, to tie it all together would make it the basis of a complete framework.