Magento – How to call a controller action from another module

controllersmagento-1.7magento-1.8module

I want to call a controller action to send email from my custom module page,

EX : my module template is ->refer.phtml
I want to call a smtp module email controller.
Module path is HTD/SMTPemail/Smtp/test

My TestController.php

class HTD_SMTPemail_Smtp_TestController extends Mage_Adminhtml_Controller_Action
{
}

How to call this controller action to send emails from refer.phtml file?

Both my phtml file and smtp controllers are in two different module.

Best Answer

To answer your question, strictly from the coding point of view, you can do what Magento does:

// @see Mage_Core_Controller_Varien_Router_Standard::match
// instantiate controller class
$controllerInstance = Mage::getControllerInstance($controllerClassName, $request, $front->getResponse());

so you could do something like:

// The action is overwritten in the action controller's constructor; to  make sure 
// there are no nasty surprises, we're going to undo this.
$originalAction = Mage::app()->getFrontController()->getAction(); 

// The action controller's constructor expects request and response objects;
$controllerInstance = Mage::getControllerInstance(
  'TD_SMTPemail_Smtp_TestController',
  new Mage_Core_Controller_Request_Http(), // you can replace this with the actual request
  new Mage_Core_Controller_Response_Http()
);

$controllerInstance->testAction();

// and undo
Mage::app()->getFrontController()->setAction($originalAction);

Now, from the logical point of view, adding this kind of logic in the template is highly not recommended. The templates are only for output; they can use some logic, but the logic has to be contained in their block class, so in the template you can only call $this->??? methods; with the exception of some minor helpers maybe, something like currency formatting for instance.

If the controller action that sends the emails is yours, you could refactor it, move the email sending logic to a model, then you can use that model in both situations, the original controller and the current controller. If the controller is not yours, then you migth wanna take a look at what models it uses and re-use those.

Cheers