Php Symfony:如何在继承控制器操作中将数据分配给模板?
我有Php Symfony:如何在继承控制器操作中将数据分配给模板?,php,symfony,twig,Php,Symfony,Twig,我有parentcontroller和继承childcontroller,它们应该将$moreData分配给模板,但是render()方法应该在parentcontroller中调用 此案例是否有任何功能/服务?我希望有类似的情况 $this->get('templating')->assignDataForTemplate('moreData',$moreData) - 我想避免类似的事情 // ... public function myAction($param1, $moreData =
parentcontroller
和继承childcontroller
,它们应该将$moreData
分配给模板,但是render()
方法应该在parentcontroller
中调用
此案例是否有任何功能/服务?我希望有类似的情况
$this->get('templating')->assignDataForTemplate('moreData',$moreData)代码>
-
我想避免类似的事情
// ...
public function myAction($param1, $moreData = null) {
return $this->render('template.html.twig', array(
'someData' => $someData,
'moreData' => $moreData
));
}
}
据我所知,目前还没有这样的方法。如果查看源代码,您将看到调用$templating->render()
实际上是调用TwigEngine->render()
。它调用将模板输出到客户端的Twig\u Template->render()
我完全理解为什么您可能会使用HMVC,但我相信这种方法可能会使事情变得过于复杂。如果控制器之间有公共代码,只需创建一个可以直接调用的静态类。然后将您的通用逻辑/代码移到那里,并在需要时调用它
否则,您可能需要继续使用您目前试图避免的代码(或类似的解决方法)。您可以尝试类似的方法,以便家长不知道孩子
<?php
class TheParentController {
public function myAction () {
$data = $this->getMyActionData();
return $this->render('template', $data);
}
protected function getMyActionData () {
return [
'someDefault' => 5
];
}
}
class TheChildController extends TheParentController {
// If using annotation based routing override myAction
// with call to parent function and new @Route tag in doc block
protected function getMyActionData () {
$parentData = parent::getMyActionData();
return array_merge($parentData, [
'childData' => 11
]);
}
}
@MattHB Symfony功能强大,我无法想象,对于这个问题没有现成的解决方案。或者也许我的架构不是Symfony的风格。我尽量避免这样的变通办法。但是谢谢。:-)
// ...
public function myAction($param1, $moreData = null) {
return $this->render('template.html.twig', array(
'someData' => $someData,
'moreData' => $moreData
));
}
}
<?php
class TheParentController {
public function myAction () {
$data = $this->getMyActionData();
return $this->render('template', $data);
}
protected function getMyActionData () {
return [
'someDefault' => 5
];
}
}
class TheChildController extends TheParentController {
// If using annotation based routing override myAction
// with call to parent function and new @Route tag in doc block
protected function getMyActionData () {
$parentData = parent::getMyActionData();
return array_merge($parentData, [
'childData' => 11
]);
}
}