子路由中的ZF2可选路由约束

Ros*_*oss 6 php zend-route zend-framework2

我在路径中的可选约束存在问题,该路径在其子项中是非可选的.我的路由结构如下:

'profile' => [
    'type' => 'segment',
    'options' => [
        'route' => '/profile[/:id]',
        'constraints' => ['id' => '[0-9]*'],
        'defaults' => [
            'controller' => 'User\Controller\User',
            'action' => 'profile'
        ]
    ],
    'may_terminate' => true,
    'child_routes' => [
        'sessions' => [
            'type' => 'literal',
            'options' => [
                'route' => '/sessions',
                'defaults' => ['action' => 'sessions']
            ]
        ]
    ]
]
Run Code Online (Sandbox Code Playgroud)

在我看来应该给我以下路线:

  1. /profile - 工作
  2. /profile/123 - 工作
  3. /profile/sessions- 不起作用
  4. /profile/123/sessions - 工作

当我在URL视图助手中使用路由3时,我收到以下错误:

$this->url('profile/sessions');
Run Code Online (Sandbox Code Playgroud)

Zend\Mvc\Router\Exception\InvalidArgumentException:缺少参数"id"

我原来[0-9]+作为我的约束,但使它成为可选(*)似乎没有帮助.以前有没有人遇到这个案子?

Mat*_*ann 8

将其添加到父路线.

'profile' => [
    'type' => 'segment',
    'options' => [                 // ? 
        'route' => '/profile[/:id][/:action]',
        'constraints' => [ 'id' => '[0-9]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*' ],
        'defaults' => [
            'controller' => 'User\Controller\User',
            'action' => 'profile',
        ],
    ],
]
Run Code Online (Sandbox Code Playgroud)

这将使其成为可选id和/或action.至少在理论上它应该使所有列出的路线成为可能,这有一些问题.


And*_*den 3

我曾经遇到过同样的问题,我发现的唯一解决方案是创建一个单独的路由(在您的情况下为 /profile/sessions )作为基本路由的可选参数,在访问子路由时似乎变得必须。

  • 我最终选择了这条路线,因为我更喜欢清楚地定义每条路线(我不喜欢“神奇的”`/:controller[/:action]` 风格的路线)。 (2认同)