Symfony:如何在继承控制器操作中将数据分配给模板?

Symfony: how to assign data to a template in an inheritating controller-action?

我有TheParentController和继承TheChildController,应该给模板赋值$moreData,但是render()方法应该在TheParentController中调用.

这个案例有function/service吗?我期待

$this->get('templating')->assignDataForTemplate('moreData', $moreData);

class TheParentController 
{
    public function myAction($param1) {
        return $this->render('template.html.twig', array(
            'someData' => $someData
        ));
    }

}

-

class TheChildController 
{
    public function myAction($param1) {
        // !
        // Is there any function like "assignDataForTemplate"?
        $this->get('templating')->assignDataForTemplate('moreData', $moreData);
        // /!
        return parent::myAction($param1);
    }
}

我想避免像

这样的事情
// ...
public function myAction($param1, $moreData = null) {
    return $this->render('template.html.twig', array(
            'someData' => $someData,
            'moreData' => $moreData
        ));
    }
}

据我所知,目前还没有这样的方法。如果您查看源代码,您会看到调用 $templating->render() 实际上是调用 TwigEngine->render()。调用 Twig_Template->render() 将模板输出到客户端。

我完全理解您使用 HMVC 的原因,但我认为这种方法可能会使您的工作过于复杂。如果控制器之间有通用代码 - 只需创建一个静态 class 即可直接调用。然后将您的公共 logic/code 移到那里,并在需要时调用它。

否则,您可能需要暂时坚持使用您试图避免(或类似的解决方法)的代码。

您可以尝试这样的操作,这样 parent 就不会知道 child。

<?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  
        ]); 
    }
}