Monday, December 24, 2012

Using Child Routes In Zend Framework 2

In Zend Framework 2, the router has support with child routes or part routes. As opposed to ZF 1 which have a flat routing heirarchy, this feature ensures that you have an organized route tree. However, child routes are not meant to be called or used directly. More so, the way to use is buried beneath the rubble of the ZF documentation.

So how, it's actually quite easy.

1. First define your child route.


 'main_url' => array(
                'type' => 'Literal',
                'options' => array(
                    'route' => '/main/url',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Main\Controller',
                        'controller' => 'Main',
                        'action' => 'url',
                    )
                ),
                'may_terminate' => true,
                'child_routes' => array (
                    'add' => array(
                        'type' => 'Literal',
                        'options' => array(
                            'route' => '/add',
                            'defaults' => array(
                            )
                        ),
                    ),
                )
            ),
2. Call your child route using the url helper using the pattern 'parent/child'.

<?php echo $this->url('main_url/add', array()); ?>

With this you can now organize your routes more cleanly and strictly follow url heirarchies.
  • Related Links Widget for Blogspot

3 comments:

Andy said...

Exactly what I was looking for - thanks!

pAwAn Singh said...

Exactly what i was looking for - thanks!

pAwAn Singh said...
This comment has been removed by the author.