ZF2,在同一个地方使用Slug或Action路线?

时间:2016-12-04 00:38:38

标签: php zend-framework zend-framework2 zend-route

我想要这条路线:

localhost/events/ -> show list of events (listAction)
localhost/events/ultra-music-festival -> show event detail
localhost/events/bob-ross -> show event detail
localhost/events/anyAction -> execute any action in EventsController.php
localhost/events/anyAction/23 -> execute any action, with optional parameter (13), in EventsController.php

我的代码:

'router' => array(
    'routes' => array(
        'events' => array(
            'type' => 'literal',
            'options' => array(
                'route' => '/events',
                'defaults' => array(
                    '__NAMESPACE__' => 'Events\Controller',
                    'module' => 'Events',
                    'controller' => 'events',
                    'action' => 'list'
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'default' => array(
                    'type' => 'segment',
                    'options' => array(
                        'route' => '[/:action[/:id]]',
                        'constraints' => array(
                            'action' => '[a-zA-Z][a-zA-z0-9_-]*',
                            'id' => '[a-zA-z0-9_-]*', // slug
                        ),
                    ),
                ),
                'detail' => array(
                    'type' => 'segment',
                    'options' => array(
                        'route' => '[/:id]',
                        'defaults' => array(
                            'action' => 'detail'
                        ),
                        'constraints' => array(
                            'id' => '[a-zA-z0-9_-]*', // slug
                        )
                    )
                ),
                'paginator' => array(
                    'type' => 'Segment',
                    'options' => array(
                        'route' => '[/:action]/page/[:page]',
                        'constraints' => array(
                            'page' => '\d+',
                        ),
                    )
                ),
            ),
        )
    )
),

此路线在以下情况下运作良好:

localhost/events/ -> show list of events (listAction)
localhost/events/ultra-music-festival -> show event detail
localhost/events/detail/ultra-music-festival -> show event detail
localhost/events/anyAction/23 -> execute any action, with optional parameter (13), in EventsController.php

此路线在以下情况下无效:

localhost/events/anyAction -> execute any action in EventsController.php

我没有找到任何解决这个Slug用例的方法,这就是我需要做的事情。 对我来说,这种类型的路线是(或应该)非常常用。 例如,如果是博客:

/blog/postname1
/blog/postname2
/blog/create
/blog/edit/1
/blog/edit/2

1 个答案:

答案 0 :(得分:0)

尝试改变这一点:

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

为:

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

附加括号导致问题。