CakePHP: best way to call an action of another controller with array as parameter?

Vicer picture Vicer · Oct 2, 2009 · Viewed 83.1k times · Source

In a controller, what is the most appropriate way to call the action of another controller and also pass an array as parameter?

I know that you can use requestAction to call actions within other controllers. But is it possible to pass arrays as parameters using request action?

And no, I do not want to put the action in the App Controller. So that is not a solution for me.

The only other way I know is to load the other controller as explained in: http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Configuration.html#importing-controllers-models-components-behaviors-views-and-helpers

But is there an easier way to just call the other controllers action while passing an array as parameter?

I am new to cakePHP so any suggestion is appreciated. Thanks.

Answer

Schaoulli picture Schaoulli · Oct 2, 2009

I would not advice to use the method requestAction but rather import, and instantiate the needed controller.

CakePHP doc says about requestAction that:

"It is rarely appropriate to use in a controller or model"

http://book.cakephp.org/view/434/requestAction

Once you imported and loaded the controller you can call any method of this controller with its parameters.

<?php
  //Import controller
  App::import('Controller', 'Posts');

  class CommentsController extends AppController {
    //Instantiation
    $Posts = new PostsController;
    //Load model, components...
    $Posts->constructClasses();

    function index($passArray = array(1,2,3)) {
      //Call a method from PostsController with parameter
      $Posts->doSomething($passArray);
    }
  }
?>