Zend Framework 3路由配置问题:访问Voucher控制器报404错误
问题分析与解决方案
嘿,我帮你定位到了两个导致/voucher路由404的关键问题,一起来看看:
1. 路由层级配置错误
你在router数组里把voucher路由和routes平级定义了,但所有路由规则都必须嵌套在router->routes数组内部。原配置中mainapp路由是正确放在routes里的,而voucher路由却跑到了routes外面,导致路由系统完全没有加载这个规则。
2. 路由约束参数名不匹配
在voucher路由的constraints配置里,你写的是'id' => '[0-9]+',但你的路由规则里使用的参数是:first_id和:second_id。约束的参数名必须和路由中的参数名严格对应,否则约束无法生效,甚至会干扰路由的正常匹配。
修正后的完整配置示例
'controllers' => [ 'factories' => [ Controller\MainappController::class => Controller\Factory\MainappControllerFactory::class, //... Controller\VoucherController::class => Controller\Factory\VoucherControllerFactory::class, //... ], ], 'router' => [ 'routes' => [ 'mainapp' => [ 'type' => Segment::class, 'options' => [ 'route' => '/mainapp[/:action[/:first_id][/:second_id]]', 'constraints' => [ 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'first_id' => '[0-9]+', 'second_id' => '[0-9]+', ], 'defaults' => [ 'controller' => Controller\MainappController::class, 'action' => 'index', ], ], ], 'voucher' => [ 'type' => Segment::class, 'options' => [ 'route' => '/voucher[/:action[/:first_id][/:second_id]]', 'constraints' => [ 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'first_id' => '[0-9]+', 'second_id' => '[0-9]+', ], 'defaults' => [ 'controller' => Controller\VoucherController::class, 'action' => 'index', ], ], ], ], ],
把配置改成上面这样,应该就能正常访问/voucher路由了。
内容的提问来源于stack exchange,提问作者ธีรพล เจริญวิเศษศิริ
相关产品推荐
相关产品推荐

