I have been thinking about a different approach to mvc for web lately. Don't know if this idea is good or bad. I'll lay it out and then you can judge for yourselves.
Key point:
- When routing everything to one file you have to mess with the normal flow of a webapplication. You add a front-controller which with the help of a router implementation figure out which controllers to load. One also oftentimes add a .htaccess file for creating pretty urls. In other words, you add complexity. Is it neccessary?
Alternate approach:
- Folders determine structure (categories, modules etc)
- When calling a controller action, one calls a file directly (/app/articles/edit.php) and in that file is the logic for that controller action
- Each controller-file include optional parent files such as configuration, db-connection, template, authorization and module-specific pre-dispatch logic. These are usually grouped together into a single include-file which is included at the top of each controller-file
- For each module in your app, you can create a different include file for your controller actions, so that you can have module-specific logic passed on to each controller-action in your module
- Use autoloading for library-classes and model-classes
A typical controller file:
PHP Code:
require 'core.inc.php';
$form = new Form_EditArticle();
if (!Request::isPost()) {
$form->populate(Model_Articles::get(Request::get('id')));
} else {
if ($form->isValid(Request::post())) {
Model_Articles::add($form->getValues());
Response::redirect('index.php');
}
}
require VIEW_PATH . 'articles/edit.php';
View file:
PHP Code:
require TEMPLATE_PATH . 'cms.php';
head('Edit article');
echo $form;
foot();
Core.inc.php file:
PHP Code:
//Define path to view files
define('VIEW_PATH', '/usr/app/views/');
//Define path to template files
define('TEMPLATE_PATH', '/usr/app/templates/');
//Include autoloader for the library
require realpath(dirname(__FILE__) . '/../../lib/autoloader.php');
//Autoloader for forms
//...
//Autoloader for models
//...
//Authentication
//....
//Db connection etc...
Pros with this approach:
- No need to mess with urls and translate them into something meaningful
- Easy to see what's going on, and how things fit together.
- No need for .htaccess
- Unlimited categories/modules/subcategories
- Easy to create actions/pages that needs to be different (like ajax responses, csv responses, upload script for images etc..)
- Easy to move modules around.
Cons:
- Not suitable for cases where you have dynamic urls (like a website that get its content and structure from a database)
- If you really don't want to have .php in your url.
Bookmarks