Posts Tagged ‘magic-code’

Using __call() in your controller to render magic content.

Saturday, December 6th, 2008

I was writing a basic CMS-type system and I was getting a bit annoyed with long urls, ie: /index/content/page/something, when I really just wanted /content/something – so I thought to myself, “self, why don’t you use __call() and just magically handle the incoming actions?

Well, self, that was a brilliant idea.

function __call($method, $params)
{
	Zend_Loader::loadClass('Zend_Filter_Inflector');
	$inflector = new Zend_Filter_Inflector(':action');

	$inflector->setRules(array(
   	 ':action'  => array('Word_CamelCaseToDash', 'StringToLower'),
	));

	$magicAction = str_replace('-action', '',
		$inflector->filter(array(':action' => $method)));

	/* TODO: lookup the magicAction in the cms table
	 * replace in_array with a check for the db_row
	 * remove $magicArray
	 */
	$magicArray = array('in-person', 'custom-experience');
	if (in_array($magicAction, $magicArray)) {
		// we have a record
		$this->render('magic-content');
	} else {
		// no record, use my magic 404 thrower.
		$this->fileNotFound();
	}
}

And with that, any of non-existent actions requested in my controller will be looked up in a db, then rendered using a common view script.  Pretty simple, really.