Making working with DB records easier with a controller helper

Tags:

The other day I noticed a pattern that repeats quite much in my code:

  • Take a parameter from the request, such as id
  • Query the DB for a record that matches the param
  • Redirect or throw a 404 exception if record was not found

Why do all this, when it could be simply a helper call?

A DB helper

Since I’m using Doctrine, I’m simply calling my helper CU_Controller_Action_Helper_Doctrine. If you’re using Zend_Db or something else, you could call it Your_Controller_Action_Helper_Db or whatever.

The idea is to make the multi-line operation of taking a parameter, querying the db and checking the result into a single line operation.

For example…

$id = $this->_getParam('id');
$record = $this->_helper->Doctrine->getRecordOrException('Article', $id);

Essentially, the above code would get an Article object with the ID from the parameter, or throw an exception if it wasn’t found, allowing you to, for example, display an error 404 page automatically.

Implementation

You can find source code for my implementation of a Doctrine helper at the svn.

Note that it throws an exception of type CU_Exception_NotFound, which you may want to change to your own class.