是否可以连接(理想情况下在控制器中)为路由添加其他参数?
我知道这听起来不太清楚,乍一看这可能听起来很荒谬 - 因为要到达控制器我们必须有路由。但我想只更改默认变量。
我会尝试解释我想要实现的目标:
配置:
return [
'router' => [
'routes' => [
'some' => [
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => [
'route' => '/some/:project',
'defaults' => [
'__NAMESPACE__' => 'Some\Controller',
'controller' => 'Some\Controller\Some',
'action' => 'some',
'extra' => 'default-value'
],
],
]
]
]
];
控制器:
class SomeController extends AbstractActionController {
protected $project = null;
public function setEventManager(EventManagerInterface $events)
{
parent::setEventManager($events);
$controller = $this;
$events->attach(
'dispatch', function (\Zend\Mvc\MvcEvent $e) use ($controller) {
$params = $e->getRouteMatch()->getParams();
$this->project = $params['project'] ;
// and there should be something that I want to
// achieve but do not know how (and if it is possible)
if ($this->project == 1) {
// magic action which modify config default param
// "extra" from "default-value" to "changed-value"
}
return;
}, 50
);
}
protected function attachDefaultListeners()
{
parent::attachDefaultListeners();
$eventManager = $this->getEventManager();
$eventManager->attach(
\Zend\Mvc\MvcEvent::EVENT_DISPATCH,
function(\Zend\Mvc\MvcEvent $event) {
$ViewModel = $event->getResult();
if ($ViewModel instanceof \Zend\View\Model\ViewModel) {
$ViewModel->setVariable('project',$this->project);
}
},
-99);
}
public function someAction() {
echo $this->params()->fromRoute("extra"); // return "default-value";
// but i want
echo $this->params()->fromRoute("extra"); // return "changed-value";
return new ViewModel();
}
}
查看
<?php
echo "project: ".$this->project;
echo $this->url('some',['project'=>1]); // result: "/some/1"
我知道这看起来很奇怪。但由于某些原因(可读链接,seo)对我来说是必要的。
答案 0 :(得分:1)
您确定要更改默认参数吗?
if ($this->project == 1) {
$e->getRouteMatch()->setParam('extra', 'changed-value');
}
您可以全局设置默认参数:
$serviceLocator->get('router')->setDefaultParam('extra', 'changed-value');
无法更改默认 - 属性 Zend \ Mvc \ Router \ Http \ Segment
如果你真的需要它,你必须扩展这个课程(但我不建议这样做,因为我认为你的方法已经错了)