Zend Framework 2 - Zend\Mvc\Router\Http\Part - Module Configuration

1.2k views Asked by At

I am creating a multi lingual application using ZF2.. and cannot determine how to add a part URL which will form the base of each URL regardless of modules.

http://localhost/en/us/application/index/index/

I totally understand how to configure /[:namespace[/:controller[/:action]]] using DI

http://localhost/application/index/index/
http://localhost/guestbook/index/index/
http://localhost/forum/index/index/

What I do not understand is how to configure a Part route which will be the base for all routes.. In ZF1 I used Route Chaining to achieve this..

So I need to configure a Part route of /[:lang[/:locale]] which applies site wide and then let the module configure /[:namespace[/:controller[/:action]]] or any other route necessary..

http://localhost/en/us/application/index/index/
http://localhost/zh/cn/application/index/index/
http://localhost/en/uk/forum/index/index/
1

There are 1 answers

2
Adam Lundrigan On BEST ANSWER

I think what you are looking for is the child_routes configuration key. Take a look at how ZfcUser configures it's routing (here): it creates a base Literal route (/user) and then chains the sub-routes (/user/login, etc) onto it via the child_routes array.

I think something like this will do the trick for you:

'router' => array(
    'routes' => array(
        'myapp' => array(
            'type' => 'Segment',
            'options' => array(
                'route' => '/[:lang[/:locale]]',
                'defaults' => array(
                    'lang'   => 'en',
                    'locale' => 'us',
                ),
            ),
            'may_terminate' => false,
            'child_routes' => array(
                'default' => array(
                    'type'    => 'Segment',
                    'options' => array(
                        'route'    => '/[:controller[/:action]]',
                        'constraints' => array(
                            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'index',
                        'action'     => 'index',
                    ),
                ),
            ),
        ),
    ),
),

Then in your controller you could do this to get the lang and locale:

$this->params()->fromRoute('lang');
$this->params()->fromRoute('locale');