zend-frameworkbootstrappingzend-controller-router

Using Zend_Controller_Router_Route to create friendly URLs for the actions in IndexController


In my IndexController, I currently have indexAction (homepage), loginAction and logoutAction. I'm trying to remove "/index/" from the URL to get domain.com/login instead of domain.com/index/login.

What is the cleanest way to achieve this? Is there a RegEx we can use? I don't ever want /index/ in the URL.

My current solution, which I believe can be improved upon, is below. Also, what does the first parameter in addRoute() do?

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initViewHelpers()
  {
    $front  = Zend_Controller_Front::getInstance();
    $router = $front->getRouter();
    $router->addRoute('login',
      new Zend_Controller_Router_Route('login/*', array(
        'controller' => 'index',
        'action'     => 'login'
      ))
    );
    $router->addRoute('logout',
      new Zend_Controller_Router_Route('logout/*', array(
        'controller' => 'index',
        'action'     => 'logout'
      ))
    );
  }
}

Solution

  • There is nothing to impove, you have to create route for every action. This will allow you to change route defaults (module/controller/action) without modifying your code.

    First parameter is the route name, which you have to use with url() helper in your views:

    <a href="<?php echo $this->url(array(), 'login', true); ?>">Login</a>
    

    Update. You can use such route, if you want only one route without "index" in url:

    $router->addRoute('default',
      new Zend_Controller_Router_Route(':action/*', array(
        'controller' => 'index',
      ))
    );