Static Routes with Zend Framework 1.8+
The standard router from the Zend Framework is awesome. You can use the standard router to perform mod-rewrite behaviors - without having to modify a single line in your .htaccess file. This post features changing a URL from something like:
http://www.example.com/index/contact/ to
http://www.example.com/contact/
There are currently six types of routes you can setup:
- Zend_Controller_Router_Route
- Zend_Controller_Router_Route_Static
- Zend_Controller_Router_Route_Regex
- Zend_Controller_Router_Route_Hostname
- Zend_Controller_Router_Route_Chain
- Default Routes
To route the example above, you can use Zend_Controller_Router_Route_Static, but the general idea applies to implementing any type of route.
The first thing you'll need to do is create a controller plugin class. For example, create the following file in your projects directory: library/my/controller/plugin/Route.php. Make sure you have the namespace "My", or whatever namespace you'd like to use, autoloaded. The simplest way to do this is add the following to the application.ini file:
autoloaderNamespaces[] = "My_"
Controller plugins contain five functions which can be registered, customizing your controllers normal behavior:
- routeStartup()
- routeShutdown
- dispatchLoopStartup()
- preDispatch()
- postDispatch()
- dispatchLoopShutdown()
The routeStartup() function is where we are going to want to customize our controllers routing behavior, since it is called right before ZF starts evaluating the URI request against its default routes.
class My_Controller_Plugin_Route extends Zend_Controller_Plugin_Abstract
{
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$contact_route = new Zend_Controller_Router_Route_Static(
"contact",
array(
"controller" => "index",
"action" => "contact"
)
);
$front_controller = Zend_Controller_Front::getInstance();
$router = $front_controller->getRouter();
$router->addRoute("contact_route", $contact_route);
}
Initializing the Zend_Controller_Router_Route_Static object is pretty self-explanatory. Now when contact, the first parameter, is directly after the domain name, ZF will route to the index controller, and contact action.
After creating the static route, grab the front controller's router. Add a name for the route and the custom route to the router. In my example, I gave it a name of 'contact_route'. Names are necessary for doing redirects, forwards, Zend_Navigation features, and probably a few more things that I'm unaware of.
And that's pretty much it!


