Search code examples
phpzend-frameworkrouteszend-framework3

Zend Framework3 similar routes conflict


I'm using ZF3, in module.config.php file in Post module, I have one of these two routes,

'create-post' => [
    'type' => Literal::class,
    'options' => [
        // Change this to something specific to your module
        'route' => '/post/create',
        'defaults' => [
            'controller' => Controller\PostController::class,
            'action' => 'create',
        ]
    ],
    'may_terminate' => true,
    'child_routes' => [
        // You can place additional routes that match under the
        // route defined above here.
    ],
],

'post' => [
    'type' => Segment::class,
    'options' => [
        // Change this to something specific to your module
        'route' => '/post[/:postId]',
        'defaults' => [
            'controller' => Controller\PostController::class,
            'action' => 'show',
        ],
        'constraints' => array(
            'postId' => '\d{4}'
        )
    ],
    'may_terminate' => true,
    'child_routes' => [
        // You can place additional routes that match under the
        // route defined above here.
    ],
]

Now when I visit http://localhost:8080/post/create it works, but when I visit http://localhost:8080/post/32, it doesn't work. It say 404 error, page not found.

Any help is much appreciated.


Solution

  • As per @jon Stirling comment on my question, I changed the constraints on post route and it worked.

    Changed 'postId' => '\d{4}' to 'postId' => '\d{1,4}'

    'post' => [
                    'type'    => Segment::class,
                    'options' => [
                        // Change this to something specific to your module
                        'route'    => '/post[/:postId]',
                        'defaults' => [
                            'controller'    => Controller\PostController::class,
                            'action'        => 'show',
                        ],
                        'constraints' => array(
                            'postId' => '\d{1,4}'
                        )
                    ],
                    'may_terminate' => true,
                    'child_routes' => [
                        // You can place additional routes that match under the
                        // route defined above here.
                    ],
                ]