Samuel Sjöberg's weblog

Skip to navigation

Improving my MVC controllers

I had a look at a two PHP Rapid Development Frameworks, Cake and PHP on Trax and this got me thinking. First of all, the frameworks seem to accomplish a lot of great stuff, but at the same time, they seem a bit enterprisey for my small to mid-sized project.

I am in no need of scaffolding, automagic ORM and ajax helpers. I like to have full control of my models and how they are persisted. I already have a form validation framework, a DB abstraction I find sane and a template solution I like. So, instead of throwing all of this out the window, I want to improve what I might still be missing and that is an OO controller as part of the MVC pattern.

The frameworks usually provide an ApplicationController, which should be sub-classed by all controllers. A dispatcher is responsible for mapping HTTP requests to a controller. If you have ever used mod_rewrite you've been using a file based dispatcher (even though you might not have thought about it like that).

Usually, there also is a concept of actions that determines how the controller behaves. An action is usually determined from the URL with help of some mapping (or routing). The example below illustrates the concept:

In Cake, actions are mapped to a function in the controller. For example, the action view would invoke the function view() with some parameters.

I have a little problem with this. Being a java developer, I like interfaces and there is no concept of that here. The dispatcher only works because we can invoke functions by what could be compared to reflection.

require_once(ROOT .'/'. $config['controller'] .'.class.php');
$class = basename($config['controller']);
$controller = &new $class();
$controller->$config['action'](); // variable-based invocation

If we go back to interfaces, I find the HttpServlet solution more appealing. The action is here reduced to the request method (i.e., GET, POST, etc.) and this determines how the controller is invoked.

This method seems appealing, so I will try it. This is the outline of what needs to be done.

I have a basic proof of concept up and running. I have successfully tried a basic (no OO) dispatcher and also the reflection approach I gave an example of above. What remains is to define my own Controller class and see how that works out. I'm still not sure what the benefits of this will be. Up until now, I have always had different files (i.e. controllers) to handle the admin and visitor views. Perhaps those days are now past as the view seldom handles POST requests. Or perhaps not, perhaps there is need for a mode that can be passed to the controller? I need to sort that out...

I will get back with more details as the experiment proceeds.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 29th December 2006 15:39 CET. Filed under PHP.

0 Pingbacks