The Dispatcher

We’ve previously defined the MVC (model-view-controller) architecture and defined how we use the URI to determine which controller and which action, or method, to use for the URI. Now we discuss what to do with the rewritten URL, and how to parse it.

How the Dispatcher Works

The dispatcher class was designed to take a URI and map it to a specific controller and action. It does this by assuming that the first part of the URI (that is, the characters before the first /) is the controller, and the second part (the characters between the first and second /), if any, is the action, and anything else are arguments to that action.

An example:

http://app.mysite.com/users/view/445

Our dispatcher class would assume that “users” is the base name of the controller class, and that “usersController” is the full name of the controller class. In OpenAvanti, all class file names for controllers must follow the format: [name]Controller.

The dispatcher would then attempt to instantiate the usersController class.

The dispatcher then assumes that the second part of the URI, “view” is the action, or method to invoke on the controller. So our dispatcher class would attempt to call the method usersController->view.

Anything after that is passed as arguments to the controller’s method (445 in our example). So when you put it all together, we’re effectively doing this after parsing the URI:

<?php
    $oUser = new UserController();
    $oUser->view( 445 );
?>

What if there is no action in the URI?

If there is no action in the URI — if our URI is simply /users, then the dispatcher attempts to call the controller’s index() method, which is the default if no action was defined:

<?php
    $oUser = new UserController();
    $oUser->index();
?>

Using the Dispatcher

Using the Dispatcher is easy. This example assumes you’ve followed our mod_rewrite example, and are rewriting the URL to index.php?request= with the URI as the value for request:

<?php
    $sRequest = isset( $_GET[ "request" ] ) ? $_GET[ "request" ] : "";
 
    Dispatcher::Connect( $sRequest );
?>

Simple, huh? What we’re telling the dispatcher to do is take the request URI and connect or map it to it’s associated controller and action.

There are more steps required to get a working example. For instance, we need to write a controller to map to, as well as some view files to load. And we should probably do something if no URI is specified, ie, if the user simply goes to www.yoursite.com. We’ll continue to discuss this more in the article on controllers.

What if the dispatcher can’t find a match?

If the dispatcher fails to find the controller, or the controller does not have the action method referenced, a 404 is thrown. See the article on handling 404s for more details.