views:

204

answers:

3

I have two controllers which have some actions that are really the same. How do I refer to the identical action in another controller?

 class UserController extends Zend_Controller_Action {

    public function listAction() {
            //do something here
    }  
 }

 class AdminController extends Zend_Controller_Action {

    public function listAction() {
            //how to call UserController::listAction here?
    }  
 }

What do I put in AdminController::listAction above so that I only have to write the code in UserController::listAction?

thanks

A: 

You can forward to another action - simply specify the action, controller, module and params.

Parameters default to values of the current request, i.e. if you're in the default module, the code below will redirect to the listAction of UserController in the default module.

class AdminController extends Zend_Controller_Action {

    public function listAction() {
            //call UserController::listAction
            return $this->_forward('list', 'user');
    }  
 }
David Caunt
+3  A: 

You could do:

class baseController extends Zend_Controller_Action {
 // common controller actions
    public function listAction() {
        // do stuff
    }
}

class AdminController extends baseController {
 // admin controller specific actions
}

class UserController extends baseController {
 // base controller specific actions
}

You could also forward the request to the other controller by using:

class AdminController extends Zend_Controller_Action {
    public function listAction() {
        $this->_forward('list','user');
    }
}

or if you would prefer the URL to change:

class AdminController extends Zend_Controller_Action {
    public function listAction() {
        $this->_redirect('/user/list');
    }
}
Richy C.
+6  A: 

I would use a controller action helper, that way if you ever have to do the same thing again you can reuse it.

class My_Controller_Action_Helper_Whatever
{
    public function direct()
    {
        return $this;
    }

    public function doSomething($paramA, $paramB)
    {
        // code
        return $whatever;
    }
}

Then implement in your controllers:

class UserController extends Zend_Controller_Action
{
    public function someAction()
    {
        $this->getHelper('Whatever')->doSomething($a, $b);
    }
}

class AdminController extends Zend_Controller_Action
{
    public function anotherAction()
    {
        $this->getHelper('Whatever')->doSomething($a, $b);
    }
}
rob