转发另一个模板


Forward with another template

我面临Symfony(v2.3)的forward方法的问题。

基本上,我在两个不同的包中有两个控制器。假设DesktopBundle用于桌面版应用程序,MobileBundle用于移动版应用程序。

我想将DesktopBundle的一个动作的代码重用为MobileBundle的动作。我现在做的是一个前锋:

桌面控制器

namespace Acme'DesktopBundle'Controller;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Template;
/**
 * @Route("/")
 */
class IndexController extends Controller
{
    /**
     * @Route("", name="desktopIndex")
     * @Template()
     */
    public function indexAction()
    {
        /* some code I don't want to duplicate */
        return array(
            'some' => 'var'
        );
    }
}

移动控制器

namespace Acme'MobileBundle'Controller;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Template;
/**
 * @Route("/")
 */
class IndexController extends Controller
{
    /**
     * @Route("", name="mobileIndex")
     * @Template()
     */
    public function indexAction()
    {
        return $this->forward('AcmeDesktopBundle:Index:index');
    }
}

现在它可以工作了,但很明显,Response对象是用桌面版indexAction的渲染模板返回的。

我想要的是获得变量,然后呈现移动版本的模板。

我尝试的是将一个变量传递到forward方法中,然后将该操作有条件地呈现到桌面版本中:

return $this->forward(
    'acmeDesktopBundle:Index:index', 
    array('mobile' => true)
);

这是可行的,但我真的不想更改为DesktopBundle中的代码,而只想更改MobileBundle中的代码。有办法做到这一点吗?我遗漏了什么,还是应该采用完全不同的解决方案?

Forwarding意味着重定向到给定的页面,但不更改客户端上的url。即在服务器端重定向。如果你只想访问操作的返回值,只需调用它。有了@Template注释,这就非常容易了。

namespace Acme'MobileBundle'Controller;
use Acme'DesktopBundle'Controller'IndexController as DesktopController;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Template;
/**
 * @Route("/")
 */
class IndexController extends Controller
{
    /**
     * @Route("", name="mobileIndex")
     * @Template()
     */
    public function indexAction()
    {
        $desktop = new DesktopController();
        $desktop->setContainer($this->container);
        $values = $desktop->indexAction();
        // do something with it
        return $values;
    }
}