[英]Inject default value in ZF2 Router
我目前有一个细分路线,如下所示: /shop/:shopId/
其中shopId
没有默认值。
每当路由匹配时,都会触发Module.php中的代码,这将根据shopId
进行一些准备并将其保存在会话中。
我的问题是,到那时是否可以设置到该shopId
的路由的默认值? 最终的目标是从此刻起,每次都无需指定shopId
即可组装URL。
我记得在ZF1中,此行为是默认情况下的,在组装URL时,将重用Request中匹配的参数,并且必须明确指定要删除它们。 现在,我需要相同的功能,但需要在Module.php
级别上进行配置,而不必重写每个assemble()
调用。
选项一:从您的indexAction
$id = $routeMatch->getParam('id', false);
if (!$id)
$id = 1; // id was not supplied set default one note this can be added as constant or from db ....
选项二:在module.config.php中设置路由
'product-view' => array(
'type' => 'Literal',
'options' => array(
'route' => '/product/view',
'defaults' => array(
'controller' => 'product-view-controller',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '[/:cat][/]',
'constraints' => array(
'cat' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
在您的控制器中:
public function indexAction()
{
// get category param
$categoryParam = $this->params()->fromRoute('cat');
// if !cat then get random category
$categoryParam = ($categoryParam) ? $categoryParam : $this->categories[array_rand($this->categories)];
$shortList = $this->listingsTable->getListingsByCategory($categoryParam);
return new ViewModel(array(
'shortList' => $shortList,
'categoryParam' => $categoryParam
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.