Zend Framework makes it incredibly easy to route various URLs to different areas of your application.
There are some standard routes that I use, but for some reason there are many developers who don't harness this power of Zend.
The time to overhaul your URLs is now.
To get started, add an action to your Bootstrap.php called _initRouter()
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initRouter()
{
}
}
The first step is to retrieve the Zend_Controller_Router_Interface from the Zend_Controller_Front object.
Add this to your _initRouter() method.
<?php
$fc = Zend_Controller_Front::getInstance();
$router = $fc->getRouter(); // Retrieve Zend_Controller_Router_Interface
Now, the exciting part! Let's create some basic routes.
<?php
$router->addRoute( 'login' , new Zend_Controller_Router_Route('/login',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'login'
)));
$router->addRoute( 'logout' , new Zend_Controller_Router_Route('/logout',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'logout'
)));
The routes above mean that if a user requests the path '/login' then they will actually be routed to:
IndexController::loginAction()
The second route would handle all requests to '/logout'. These would be routed to:
IndexController::logoutAction()
Ready to kick it up a gear? The Zend_Controller_Router_Interface also makes it incredibly easy to assign request parameters without having to mess around with keys in a URL.
For example, if you added this route to your _initRouter() method:
<?php
$router->addRoute( 'userprofile' , new Zend_Controller_Router_Route('/profile/:userid',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'profile'
)));
Then all requests matching '/profile/xxxx' would be sent to:
IndexController::profileAction()
But there's something special going on here. Inside of profileAction() you could call the 'userid' request param directly and retrieve its value.
<?php
$userId = $this->getRequest()->getParam('userid',null);
The variable $userId would now contain whatever came after '/profile/' in the Url.
You can really get creative with Routes, and I've hardly touched the surface of the capability, but as you can see, this is absolutely simple.
