Often in modern websites, particularly social websites, the urls are in the format of http://somesite.com/username. This presents something of a problem for web apps that follow the MVC pattern and direct all requests through a single front controller that then dispatches the request to the correct controller based on the url or on a route set up in the app. Recently I have begun work on a website, groups.ie and I wanted to implement a url pattern of http://groups.ie/the-group-name . So how so we achieve this when we cannot properly map this using a route as the group name could be almost anything?
I achieve this by using a simple Zend plugin. Here is the code:

/**
* Description of GroupFilter
* allows for urls to follow the format of
* sitename/group-name
*
* @author craigbrookes
*/
class Application_Plugin_GroupFilter extends Zend_Controller_Plugin_Abstract {

public function preDispatch(Zend_Controller_Request_Abstract $request) {
$controller = $request->getControllerName();
$groupMapper = new Application_Model_GroupsMapper();
$group = $groupMapper->findRowByFieldsAndValues(array("url"=>$controller));

if(!$group->isEmpty()){

$request->setControllerName("group");
}
}

}

So in this code, I extend the Zend_Controller_Plugin_Abstract which provides several hook functions (functions which the parent or a controller will call on all plugins at certain times during execution)

The hook functions provided are:

  • routeStartup(): prior to routing the request
  • routeShutdown(): after routing the request
  • dispatchLoopStartup(): prior to entering the dispatch loop
  • preDispatch(): prior to dispatching an individual action
  • postDispatch(): after dispatching an individual action
  • dispatchLoopShutdown(): after completing the dispatch loop

In the above code I choose only to implement the preDispatch() which is past the instance of
Zend_Controller_Request_Abstract. From this request object I get the current controller which my be set to the name of a group. I then use my Mapper class and check if there is a group that responds to the controller name. Finally, if there is a group object found, then I set the controller to the Groups controller which can then take over. Other wise the request continues along its merry way. Got any other solutions or can see potential problems with my solution, please leave a comment and let me know.

For more information on plugins, I found this article to be quite useful.

Sorry, the comment form is closed at this time.

   
© 2012 Craig Brookes Suffusion theme by Sayontan Sinha