Martin
Martin

Reputation: 91

Call another controller action in Zend and stay in current action

I want to call another controller action, but stay in my current. I just want to run the code in the other action.

To be specific: I have a controller action for sending an email.

class StreitController extends Zend_Controller_Action {

    // Fill and send mail
    public function emailAction() {

        $this->_helper->layout->disableLayout();

        // ... do something ...

        // Capture output and send mail
        $htmlString = $this->view->render('task/email.phtml');
        $this->sendMail($this->view->task['TASK_NAME'], $htmlString, $this->view->task['TASK_EMAIL']);
    }
}

The action above should be called by this one:

class TaskController extends Zend_Controller_Action {

    public function runAction() {

        // do something

        // Now send the mail
        $this->_helper->redirector('email', 'task', 'ic', array('TASK_ID' => $this->getParam('TASK_ID')));
        $this->getRequest()->clearParams();
    }

}

The runAction modifies some data. After that the email action should be called to fill the email template (a .phtml file) and send it to the receiver. But this should happen transparent. So I don't want to leave the calling runAction. Is this somehow possible?

Upvotes: 1

Views: 1463

Answers (1)

David Weinraub
David Weinraub

Reputation: 14184

Looks like you can use the forward() method, as long as it is the last thing you want to do in that action:

$this->forward('email', 'task');

But I would advise against it.

Whenever you have a piece of code that has multiple by multiple consumers, I think it's better to refactor that code into its own class/method and then have the consumers instantiate/call.

For example, you could put that "send email" code into an action-helper. This provides a kind of lazy-load, on-demand mechanism for invoking functionality.

In your specific case, a quick-and-dirty way to make that "sending email" code available in multiple actions is to pull it up into method on a BaseController and have both TaskController and StreitController extend BaseController.

Note that, in general, action-helpers are more desirable than base controllers in that using a base controller will require all that code to be loaded even if it is not used.

Upvotes: 1

Related Questions