Php 在ZF2路由器中注入默认值
我目前有一个类似这样的段路由:Php 在ZF2路由器中注入默认值,php,zend-framework,zend-framework2,router,zend-router,Php,Zend Framework,Zend Framework2,Router,Zend Router,我目前有一个类似这样的段路由:/shop/:shopId/,其中shopId没有默认值 只要路由匹配,就会触发Module.php中的代码,这将根据shopId进行一些准备,并将其保存在会话中 我的问题是,如果可能的话,在这一点上,将路由的默认值设置为该shopId?最终的目标是,从现在起,每次组装URL时都不需要指定shopId 我记得在ZF1中,这种行为是默认的,在组装URL时重用请求中匹配的参数,并且必须明确指定要删除这些参数。现在我需要相同的功能,但配置在Module.php级别,而不必
/shop/:shopId/
,其中shopId
没有默认值
只要路由匹配,就会触发Module.php中的代码,这将根据shopId
进行一些准备,并将其保存在会话中
我的问题是,如果可能的话,在这一点上,将路由的默认值设置为该shopId
?最终的目标是,从现在起,每次组装URL时都不需要指定shopId
我记得在ZF1中,这种行为是默认的,在组装URL时重用请求中匹配的参数,并且必须明确指定要删除这些参数。现在我需要相同的功能,但配置在
Module.php
级别,而不必重写每个assemble()
调用。选项一:从索引操作
$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
));
}
选项一:从你的索引
$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
));
}