jcropp
jcropp

Reputation: 1246

How to avoid minor routing errors in ZF2

Is there a way to write routing scripts in ZF2 so that lone parameter escapes don’t lead to error messages? In the Album module, for example, the routing is set up like this:

// …

'router' => array(
    'routes' => array(
        'album' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/album[/:action][/:id]',
                'constraints' => array(
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'     => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'Album\Controller\Album',
                    'action'     => 'index',

// …

In this scenario, the url mydomain/album will route to the index view, and the url mydomain/album/index will also route to the index view; but the url mydomain/album/ will cause an error message. In an effort to anticipate some of the ‘typos’ that users might make and treat them accordingly, is there a way to write routing scripts so that mydomain/album/ works as well? Also, is there a way to route all imperfect urls that are not matched by routing to a page that provides further instructions?

Upvotes: 0

Views: 74

Answers (1)

Crisp
Crisp

Reputation: 11447

In the Album module, for example, the routing is set up like this

It was set up like that in earlier versions of the manual. It's now set up like this, which does exactly what you need.

'route'    => '/album[/][:action][/:id]',

As you can see the trailing slash after /album is itself defined as an optional parameter [/] so it matches both /album and /album/

See: http://framework.zend.com/manual/2.3/en/user-guide/routing-and-controllers.html#routing-and-controllers

As an aside, if you care about SEO, it's worth paying attention to Google's recommendations on duplicate content if you go with this, since you now have 2 distinct urls matching the same content (3 if you include the optional /index action.)

Upvotes: 2

Related Questions