Page 1 of 1

MVC error handling question

Posted: Thu Sep 21, 2006 6:00 am
by georgeoc
Hi,

I've been putting together a very basic MVC pattern for my admin interface. I'm sure it doesn't match up to most implementations, and that there are horrifying design errors, but it does what I want and seems to work very well. It's certainly made my coding process for new pages much simpler.

I have a question about handling errors. If the controller detects a $_POST['action'] key, it runs the method in the model which corresponds to that action. If at any stage of the model's method an error is generated, I need to return the error to the controller so the controller can generate a user error and halt the process.

At the moment, I have lines like this in the controller:

Code: Select all

if (FALSE === $conf = $this->_model->get_conf()) $this->make_user_error('Bad or missing configuration file. Please re-enter your settings.', 'install', 'conf');
		if (TRUE !== $message = $this->_model->connect_configured_db($conf)) $this->make_user_error($message, 'install', 'conf');
		if (TRUE !== $message = $this->_model->install_database_tables()) $this->make_user_error($message, 'install', 'conf');
		if (TRUE !== $message = $this->_model->populate_db()) $this->make_user_error($message, 'install', 'conf');
where make_user_error() is like this:

Code: Select all

function make_user_error($msg, $module = 'index', $page = NULL)
In general, the model returns TRUE on success or an error string on failure. My question is whether there's a better way to do this? It seems like overkill, and makes it hard to read, to keep writing

Code: Select all

if (TRUE !== $message =    ........     $this->make_user_error(

all the time.

Any suggestions?

Posted: Thu Sep 21, 2006 6:49 am
by georgeoc
N.B. Please note - I'm writing for PHP4 and PHP5, so any answers must be PHP4 compatible.

The alternative I can think of is to allow the model to contact the controller directly. If the model encounters an error, it can run the user_error() method on the controller. Either the model needs an instance of the controller to work on (I can't think how to do this), or it runs a static method (my_controller_class::make_user_error()). The problem with this is that somehow the controller needs to know the module and page to redirect to, and the model shouldn't really be aware of these while it does its processing. If I run make_user_error() statically, it won't have access to the controller's member variables, $module and $page. I suppose I could use another static function which stores these two values in static variables.