Reputation: 8189
I'm facing a problem with the forward
method of Symfony (v2.3).
Basicly, I have two controllers in two distinct bundles. Let's say DesktopBundle
for a desktop version of the app, and MobileBundle
for the mobile version.
I want to reuse code of an action of the DesktopBundle
into an action of MobileBundle
. What I do now is a forward :
DesktopController
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'
);
}
}
MobileController
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');
}
}
Now it works, but obviously the Response
object is returned with the rendered template of the desktop version of the indexAction
.
What I would like, is to get the variables and then render the template of the mobile version.
What I tried is to pass a variable into the forward method and then render the action conditionally into the desktop version:
return $this->forward(
'acmeDesktopBundle:Index:index',
array('mobile' => true)
);
This would work, but I don't really want to change to code inside the DesktopBundle
but only the MobileBundle
. Is there a way to achieve this ? I am missing something, or should I go to an entirely different solution ?
Upvotes: 0
Views: 765
Reputation: 10085
Forwarding means to redirect to the given page, but without changing the url on the client. I.e. redirect on the server side. If you want only access the return value of the action, simply call it. With the @Template
annotation this is made very easy.
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;
}
}
Upvotes: 2